diff --git a/README.md b/README.md index 8f7f2fe..83363a0 100644 --- a/README.md +++ b/README.md @@ -43,12 +43,13 @@ Cookies only: local storage and IndexedDB stay on your machine, so sites that ke Sites that only accept sign-ins from your network or your IP can be reached by linking this computer: your agents' browser connects to them from here. On macOS or Linux, after `gumloop login`: ```bash -gumloop browser proxy link # automatically runs in the background on startup -gumloop browser proxy status +gumloop browser proxy link # automatically runs in the background on startup +gumloop browser proxy link --foreground # stays connected from this terminal until Ctrl-C +gumloop browser proxy status -v gumloop browser proxy unlink ``` -On Linux without a systemd user session, such as a container, `link` can't run it in the background. Run `gumloop browser proxy connect` and keep it open instead. +On Linux without a systemd user session, such as a container, `link` can't run it in the background. Run `gumloop browser proxy link --foreground` and keep it open instead. The computer only opens connections to public addresses on ports 80 and 443. Its key stays in the OS keychain. `gumloop logout` unlinks it. A network that inspects TLS traffic can't be used, since sites would show the agent's browser certificate errors. diff --git a/src/gumloop/_version.py b/src/gumloop/_version.py index 62ec344..7db76f6 100644 --- a/src/gumloop/_version.py +++ b/src/gumloop/_version.py @@ -1,3 +1,3 @@ from __future__ import annotations -__version__ = "0.5.17" +__version__ = "0.5.18" diff --git a/src/gumloop/cli/commands/custom_proxy.py b/src/gumloop/cli/commands/custom_proxy.py index 056d19e..94c90cf 100644 --- a/src/gumloop/cli/commands/custom_proxy.py +++ b/src/gumloop/cli/commands/custom_proxy.py @@ -6,6 +6,7 @@ import os import socket import sys +import time from datetime import datetime from datetime import timezone from typing import Annotated @@ -44,6 +45,7 @@ from gumloop.cli.custom_proxy_lock import custom_proxy_lock from gumloop.cli.custom_proxy_lock import is_running from gumloop.cli.custom_proxy_service import CustomProxyService +from gumloop.cli.custom_proxy_service import CustomProxyServiceDetails from gumloop.cli.custom_proxy_service import NoBackgroundService from gumloop.cli.custom_proxy_service import executable_version from gumloop.cli.custom_proxy_service import gumloop_executable @@ -88,11 +90,17 @@ _RETRIED_STATUSES = frozenset({408, 409, 429}) # Gumloop answered 401 to a login that can't be refreshed, such as a revoked API key. _LOGIN_REJECTED = "login_rejected" +_CONNECT_WAIT_SECONDS = 10.0 +_STOP_WAIT_SECONDS = 5.0 +_POLL_SECONDS = 0.25 @proxy_app.command( "link", - epilog="Examples:\n gumloop browser proxy link\n gumloop browser proxy link --name 'Office desktop'", + epilog=( + "Examples:\n gumloop browser proxy link\n gumloop browser proxy link --name 'Office desktop'\n" + " gumloop browser proxy link --foreground" + ), ) def link( ctx: typer.Context, @@ -102,10 +110,23 @@ def link( "--name", help="Name for this computer in Gumloop when it is first linked. Default: its hostname." ), ] = None, + foreground: Annotated[ + bool, + typer.Option( + "--foreground", + help="Run in the foreground instead of as a background service.", + ), + ] = False, + verbose: Annotated[ + bool, + typer.Option("--verbose", "-v", help="With --foreground, show each site agents open."), + ] = False, + yes: Yes = False, ) -> None: - """Link this computer and keep it connected in the background, also after a restart.""" + """Link this computer and keep it connected in the background, or in this terminal with --foreground.""" cli: CliContext = ctx.obj host = backend_host(cli.effective_base_url) + started = datetime.now(timezone.utc) try: if not _signed_in(host): raise GumloopError(f"Run `gumloop login` first. Linking this computer needs a stored login for {host}.") @@ -120,7 +141,19 @@ def link( service: CustomProxyService | None = service_for_current_platform() except NoBackgroundService: service = None - executable = gumloop_executable() if service is not None else None + service_installed = service is not None and service.is_installed() + if (foreground or service is not None) and not service_installed and is_running(host): + raise GumloopError( + "This computer is already connected from a terminal. Stop it there with Ctrl-C, then run this again." + ) + if foreground and service_installed: + confirm_or_exit( + warning="This computer is already connected from a background service.", + question="Stop it and connect from here instead?", + yes=yes, + json_output=False, + ) + executable = gumloop_executable() if service is not None and not foreground else None check_tls_not_inspected() key = load_or_create_key(host) registration = load_registration(host) @@ -129,19 +162,26 @@ def link( "This computer is linked to another Gumloop user. Run `gumloop browser proxy unlink`, then link again." ) _register(cli, host, key, name, registration) - if service is not None and executable is not None: + if foreground and service is not None and service_installed: + service.remove() + elif service is not None and executable is not None: service.install(executable) except TlsInspected as error: exit_with_error(_tls_inspected_error(error)) except (GumloopError, ValidationError, httpx.HTTPError) as error: exit_with_error(_explained(error)) + if foreground: + _wait_until_stopped(host) + _connect(host, verbose=verbose) + return if service is None or executable is None: console.print( "It can't stay connected in the background: this computer has no systemd user session. " - "Run `gumloop browser proxy connect` and keep it open, for example in tmux." + "Run `gumloop browser proxy link --foreground` and keep it open, for example in tmux." ) return + _print_first_connection(_wait_for_connection(host, started)) if sys.platform.startswith("linux"): console.print("[dim]It connects when you log in, once your keyring is unlocked.[/dim]") service_version = executable_version(executable) @@ -157,6 +197,10 @@ def link( def status( ctx: typer.Context, json_output: Annotated[bool, typer.Option("--json", help="Print the status as JSON.")] = False, + verbose: Annotated[ + bool, + typer.Option("--verbose", "-v", help="Show more detail."), + ] = False, ) -> None: """Show whether this computer is linked and whether it is connected.""" cli: CliContext = ctx.obj @@ -164,6 +208,7 @@ def status( registration = load_registration(host) service = _service_or_none() service_installed = service is not None and service.is_installed() + service_details = service.describe() if service is not None and service_installed else None running = registration is not None and is_running(host) connection = load_connection_status(host) if running else None if registration is None: @@ -178,10 +223,25 @@ def status( "backend": host, "custom_proxy_id": registration.custom_proxy_id if registration else None, "name": registration.name if registration else None, + "user_id": registration.user_id if registration else None, "service_installed": service_installed, + "service_kind": service_details.kind if service_details else None, + "service_path": str(service_details.path) if service_details else None, + "service_executable": ( + str(service_details.executable_path) + if service_details and service_details.executable_path + else None + ), + "service_log": service_details.log if service_details else None, "state": state, "since": connection.since.isoformat() if connection else None, "last_error": connection.last_error if connection else None, + "running_since": _iso(connection.running_since) if connection else None, + "pid": connection.pid if connection else None, + "cli_version": connection.cli_version if connection else None, + "reconnects": connection.reconnects if connection else None, + "last_disconnect_at": _iso(connection.last_disconnect_at) if connection else None, + "last_disconnect_reason": connection.last_disconnect_reason if connection else None, } ) return @@ -191,14 +251,23 @@ def status( return prefix = f'"{escape_markup(registration.name)}"' if not running: - start = "link" if service is not None else "connect" + start = "link" if service is not None else "link --foreground" console.print(f"{prefix}: not running. Run `gumloop browser proxy {start}` to start.") elif connection and connection.connected: - console.print(f"{prefix}: connected since {_clock_time(connection.since)}.") + restarted = ( + f", running since {_clock_time(connection.running_since)}" + if connection.running_since and connection.reconnects + else "" + ) + console.print( + f"{prefix}: connected for {_duration(connection.since)} (since {_clock_time(connection.since)}){restarted}." + ) elif connection and connection.last_error: console.print(f"{prefix}: connecting. Last attempt failed: {escape_markup(connection.last_error)}.") else: console.print(f"{prefix}: connecting.") + if verbose: + _print_details(host, registration, connection, service, service_details) @proxy_app.command("unlink") @@ -248,7 +317,7 @@ def remove_stored_login_custom_proxy() -> bool: return remove_custom_proxy(CliContext(credentials=credentials), _login_host(credentials)) -@proxy_app.command("connect") +@proxy_app.command("connect", hidden=True) def connect( ctx: typer.Context, verbose: Annotated[ @@ -256,10 +325,13 @@ def connect( typer.Option("--verbose", "-v", help="Show more detail while connected."), ] = False, ) -> None: - """Keep this computer connected from this terminal until you stop it with Ctrl-C.""" - # The background service runs this too. A clean exit means the service should stay down. + """Run the personal proxy for the background service.""" cli: CliContext = ctx.obj - host = backend_host(cli.effective_base_url) + _connect(backend_host(cli.effective_base_url), verbose=verbose) + + +def _connect(host: str, *, verbose: bool) -> None: + """A clean exit means the background service should stay down.""" custom_proxy_id: str | None = None try: with custom_proxy_lock(host): @@ -277,13 +349,10 @@ def connect( ) return check_tls_not_inspected() - announced = False + recorder = _ConnectionRecorder(host) def on_connected() -> None: - nonlocal announced - _record_connection(host, connected=True) - if not announced: - announced = True + if recorder.connected(): console.print( "[green]Connected.[/green] Agents can now send browser traffic through this computer. " "Press Ctrl-C to stop." @@ -297,9 +366,8 @@ def on_connected() -> None: gateway_token=lambda: _gateway_token(host, registration), on_open=_print_destination if verbose else None, on_connected=on_connected, - on_failed=lambda error: _record_connection(host, connected=False, last_error=error), + on_failed=recorder.failed, ) - _record_connection(host, connected=False) try: asyncio.run(connection.run()) finally: @@ -340,6 +408,8 @@ def on_connected() -> None: ) except KeyboardInterrupt: console.print("Stopped.") + if _service_or_none() is not None: + console.print("Run `gumloop browser proxy link` to keep this computer connected in the background.") except GumloopError as error: exit_with_error(error) @@ -474,11 +544,153 @@ def _tls_inspected_error(error: TlsInspected) -> GumloopError: ) -def _record_connection(host: str, *, connected: bool, last_error: str | None = None) -> None: - save_connection_status( - host, - CustomProxyConnectionStatus(connected=connected, since=datetime.now(timezone.utc), last_error=last_error), - ) +class _ConnectionRecorder: + """Keeps this process's connection status file current, and logs disconnects and + reconnects to stderr, which the background service keeps.""" + + def __init__(self, host: str) -> None: + self._host = host + now = datetime.now(timezone.utc) + self._status = CustomProxyConnectionStatus( + connected=False, since=now, running_since=now, pid=os.getpid(), cli_version=__version__ + ) + self._has_connected = False + self._logged_failure: str | None = None + save_connection_status(host, self._status) + + def connected(self) -> bool: + """Returns whether this is the process's first connect.""" + first = not self._has_connected + self._has_connected = True + self._logged_failure = None + self._save(connected=True, last_error=None, reconnects=self._status.reconnects + (0 if first else 1)) + if not first: + _log("Reconnected.") + return first + + def failed(self, reason: str) -> None: + if self._status.connected: + self._save( + connected=False, + last_error=reason, + last_disconnect_at=datetime.now(timezone.utc), + last_disconnect_reason=reason, + ) + _log(f"Disconnected: {reason}.") + else: + self._save(connected=False, last_error=reason) + if reason != self._logged_failure: + _log(f"Couldn't connect: {reason}.") + self._logged_failure = reason + + def _save(self, **changes: object) -> None: + self._status = self._status.model_copy(update={"since": datetime.now(timezone.utc), **changes}) + save_connection_status(self._host, self._status) + + +def _wait_for_connection(host: str, started: datetime) -> CustomProxyConnectionStatus | None: + """Ignores a status file left by a process started before ``started``.""" + deadline = time.monotonic() + _CONNECT_WAIT_SECONDS + while True: + status = load_connection_status(host) + # A process running an older CLI writes no running_since. + if status is not None and (status.running_since or status.since) < started: + status = None + if (status is not None and status.connected) or time.monotonic() >= deadline: + return status + time.sleep(_POLL_SECONDS) + + +def _print_first_connection(status: CustomProxyConnectionStatus | None) -> None: + if status is not None and status.connected: + console.print("[green]Connected.[/green] Agents can now send browser traffic through this computer.") + elif status is not None and status.last_error: + console.print( + f"Still connecting. Last attempt failed: {escape_markup(status.last_error)}. " + "Check again with `gumloop browser proxy status`." + ) + else: + console.print("Still connecting. Check again with `gumloop browser proxy status`.") + + +def _wait_until_stopped(host: str) -> None: + """A stopped background service can take a moment to let go of the lock.""" + deadline = time.monotonic() + _STOP_WAIT_SECONDS + while is_running(host) and time.monotonic() < deadline: + time.sleep(_POLL_SECONDS) + + +def _print_details( + host: str, + registration: CustomProxyRegistration, + connection: CustomProxyConnectionStatus | None, + service: CustomProxyService | None, + service_details: CustomProxyServiceDetails | None, +) -> None: + rows = [ + ("Backend", host), + ("Personal proxy ID", registration.custom_proxy_id), + ("User ID", registration.user_id or "unknown"), + ] + if connection is not None: + process = [ + f"PID {connection.pid}" if connection.pid else None, + f"Gumloop CLI {connection.cli_version}" if connection.cli_version else None, + f"running since {_clock_time(connection.running_since)}" if connection.running_since else None, + ] + rows.append(("Process", ", ".join(part for part in process if part) or "unknown")) + reconnects = str(connection.reconnects) + if connection.last_disconnect_at: + reconnects += f", last disconnected at {_clock_time(connection.last_disconnect_at)}" + if connection.last_disconnect_reason: + reconnects += f": {connection.last_disconnect_reason}" + rows.append(("Reconnects", reconnects)) + if service is None: + rows.append(("Background service", "not available on this computer")) + elif service_details is None: + rows.append(("Background service", "not installed")) + else: + rows.append(("Background service", f"{service_details.kind} at {service_details.path}")) + rows.append(("Service runs", str(service_details.executable_path or "unknown"))) + rows.append(("Log", service_details.log)) + for label, value in rows: + console.print(f" [dim]{label}:[/dim] {escape_markup(value)}", highlight=False, soft_wrap=True) + if connection is not None and connection.cli_version and connection.cli_version != __version__: + restart = ( + "Run `gumloop browser proxy link` to restart it." + if service_details is not None + else "Stop it with Ctrl-C and run `gumloop browser proxy link --foreground` to restart it." + ) + console.print( + f"[yellow]Note:[/yellow] the running personal proxy is Gumloop CLI " + f"{escape_markup(connection.cli_version)}, not {__version__}. {restart}" + ) + + +def _log(message: str) -> None: + error_console.print(f"[dim]{_timestamp()}[/dim] {escape_markup(message)}", highlight=False, soft_wrap=True) + + +def _timestamp() -> str: + return datetime.now().astimezone().strftime("%b %-d, %-I:%M:%S %p") + + +def _iso(moment: datetime | None) -> str | None: + return moment.isoformat() if moment else None + + +def _duration(since: datetime) -> str: + minutes = int((datetime.now(timezone.utc) - since).total_seconds() // 60) + if minutes < 1: + return "less than a minute" + days, minutes = divmod(minutes, 24 * 60) + hours, minutes = divmod(minutes, 60) + parts = [ + f"{days} day{'s' if days != 1 else ''}" if days else None, + f"{hours} h" if hours else None, + f"{minutes} min" if minutes and not days else None, + ] + return " ".join(part for part in parts if part) def _clock_time(moment: datetime) -> str: @@ -489,5 +701,4 @@ def _clock_time(moment: datetime) -> str: def _print_destination(target: Target) -> None: - opened = datetime.now().astimezone().strftime("%b %-d, %-I:%M:%S %p") - console.print(f"[dim]{opened} {escape_markup(target.host)}[/dim]", highlight=False) + console.print(f"[dim]{_timestamp()} {escape_markup(target.host)}[/dim]", highlight=False) diff --git a/src/gumloop/cli/custom_proxy_key.py b/src/gumloop/cli/custom_proxy_key.py index 89f91aa..fd06427 100644 --- a/src/gumloop/cli/custom_proxy_key.py +++ b/src/gumloop/cli/custom_proxy_key.py @@ -59,6 +59,14 @@ class CustomProxyConnectionStatus(BaseModel): # When this status was recorded: the connect, or the start of the current attempt or failure. since: datetime last_error: str | None = None + # Defaults let `status` read the file from a process still running an older CLI. + running_since: datetime | None = None + pid: int | None = None + cli_version: str | None = None + # Connects after this process's first one. + reconnects: int = 0 + last_disconnect_at: datetime | None = None + last_disconnect_reason: str | None = None def backend_host(base_url: str) -> str: diff --git a/src/gumloop/cli/custom_proxy_service.py b/src/gumloop/cli/custom_proxy_service.py index 6c1bb11..b153076 100644 --- a/src/gumloop/cli/custom_proxy_service.py +++ b/src/gumloop/cli/custom_proxy_service.py @@ -13,6 +13,7 @@ import tempfile from collections.abc import Callable from collections.abc import Sequence +from dataclasses import dataclass from pathlib import Path from typing import Protocol @@ -42,6 +43,15 @@ class NoBackgroundService(GumloopError): as a Linux container or SSH session without a systemd user session.""" +@dataclass(frozen=True) +class CustomProxyServiceDetails: + kind: str + path: Path + # None when the service isn't installed or its file can't be read. + executable_path: Path | None + log: str + + class CustomProxyService(Protocol): def install(self, executable_path: Path) -> None: """Writes the service and (re)starts it.""" @@ -51,6 +61,8 @@ def remove(self) -> None: ... def is_installed(self) -> bool: ... + def describe(self) -> CustomProxyServiceDetails: ... + class LaunchAgentService: def __init__( @@ -68,8 +80,12 @@ def __init__( def plist_path(self) -> Path: return self._home / "Library" / "LaunchAgents" / f"{LAUNCH_AGENT_LABEL}.plist" + @property + def log_path(self) -> Path: + return self._home / ".gumloop" / "custom-proxy" / "service.log" + def install(self, executable_path: Path) -> None: - log_path = self._home / ".gumloop" / "custom-proxy" / "service.log" + log_path = self.log_path try: log_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) except OSError as error: @@ -98,6 +114,18 @@ def remove(self) -> None: def is_installed(self) -> bool: return self.plist_path.is_file() + def describe(self) -> CustomProxyServiceDetails: + executable_path = None + try: + arguments = plistlib.loads(self.plist_path.read_bytes()).get("ProgramArguments") + if isinstance(arguments, list) and arguments and isinstance(arguments[0], str): + executable_path = Path(arguments[0]) + except (OSError, ValueError, AttributeError): + pass + return CustomProxyServiceDetails( + kind="LaunchAgent", path=self.plist_path, executable_path=executable_path, log=str(self.log_path) + ) + def _job_target(self) -> str: return f"gui/{self._get_uid()}/{LAUNCH_AGENT_LABEL}" @@ -140,6 +168,23 @@ def remove(self) -> None: def is_installed(self) -> bool: return self.unit_path.is_file() + def describe(self) -> CustomProxyServiceDetails: + executable_path = None + try: + for line in self.unit_path.read_text(encoding="utf-8").splitlines(): + if line.startswith("ExecStart="): + executable = _systemd_unquote_first(line.removeprefix("ExecStart=")) + executable_path = Path(executable) if executable else None + break + except (OSError, UnicodeDecodeError): + pass + return CustomProxyServiceDetails( + kind="systemd user unit", + path=self.unit_path, + executable_path=executable_path, + log=f"journalctl --user -u {SYSTEMD_UNIT}", + ) + def _systemctl(self, *args: str) -> subprocess.CompletedProcess[str]: return self._run_command(["systemctl", "--user", *args]) @@ -179,6 +224,24 @@ def _systemd_quote(value: str) -> str: return f'"{escaped}"' +def _systemd_unquote_first(command: str) -> str | None: + """The first argument of a command written with ``_systemd_quote``.""" + if not command.startswith('"'): + return None + characters: list[str] = [] + index = 1 + while index < len(command): + character = command[index] + if character == '"': + return "".join(characters).replace("%%", "%").replace("$$", "$") + if character == "\\" and index + 1 < len(command): + index += 1 + character = command[index] + characters.append(character) + index += 1 + return None + + def _write_private(destination: Path, content: bytes) -> None: try: destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md index 1c5c7a1..b800179 100644 --- a/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md +++ b/src/gumloop/cli/plugin_assets/gumloop/skills/gumloop-cli/references/commands.md @@ -157,7 +157,8 @@ gumloop sync --once --non-interactive # one-shot sync; requires GUMLOOP_API_KEY ```bash gumloop browser proxy link # automatically runs in the background on startup -gumloop browser proxy status +gumloop browser proxy link --foreground # stays connected from this terminal until Ctrl-C +gumloop browser proxy status [-v] [--json] gumloop browser proxy unlink [--yes] ``` diff --git a/tests/cli/test_custom_proxy_command.py b/tests/cli/test_custom_proxy_command.py index 26f4137..91da611 100644 --- a/tests/cli/test_custom_proxy_command.py +++ b/tests/cli/test_custom_proxy_command.py @@ -104,6 +104,7 @@ def service(monkeypatch) -> FakeService: monkeypatch.setattr("gumloop.cli.commands.custom_proxy.check_tls_not_inspected", lambda: None) monkeypatch.setattr("gumloop.cli.commands.custom_proxy.executable_version", lambda executable: __version__) monkeypatch.setattr("gumloop.cli.commands.custom_proxy.socket", FixedHostname()) + monkeypatch.setattr("gumloop.cli.commands.custom_proxy._CONNECT_WAIT_SECONDS", 0) save_credentials(Credentials(api_key="key", user_id="actor")) return fake