diff --git a/.gitignore b/.gitignore index 1e46fbf..22130f4 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ build/ # venv .venv/ +tests/node_modules/ # uv uv.lock @@ -23,4 +24,4 @@ uv.lock Thumbs.db .env -.local \ No newline at end of file +.local diff --git a/Dockerfile b/Dockerfile index 5fcbbfd..78a5bff 100644 --- a/Dockerfile +++ b/Dockerfile @@ -66,6 +66,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ xauth xdotool xclip scrot libreoffice libreoffice-gtk3 pulseaudio pulseaudio-utils \ && rm -rf /var/lib/apt/lists/* +# Xfce's default backdrop, converted to PNG for its image loader. +COPY assets/home.webp /tmp/wallpaper.webp +RUN convert /tmp/wallpaper.webp /usr/share/backgrounds/xfce/open-webui.png \ + && ln -sf open-webui.png /usr/share/backgrounds/xfce/xfce-x.svg \ + && rm /tmp/wallpaper.webp + # Debian's launcher resets CHROMIUM_FLAGS before reading this directory. RUN printf '%s\n' \ 'case "${OPEN_TERMINAL_BROWSER_NO_SANDBOX:-false}" in' \ diff --git a/README.md b/README.md index 0948c1b..7a4651c 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,22 @@ If no API key is configured, one is generated and printed at startup. For Docker > [!CAUTION] > The API key grants command and file access. On bare metal, commands run with your user's permissions. Give access only to people and agents you trust. +### Private local IPC + +Desktop clients can use the existing HTTP/WebSocket API without opening a TCP listener: + +```bash +# macOS/Linux: use a socket inside a directory owned by the current user (mode 0700). +open-terminal run --isolated --ipc /path/to/private-directory/api.sock +``` + +On Windows, use a local named pipe, for example +`open-terminal run --isolated --ipc \\.\pipe\open-terminal-private`. +API-key authentication still applies. `--port 8000` adds a TCP listener; +it binds to `127.0.0.1` unless `--host 0.0.0.0` is explicitly supplied. +Use port `0` to select an available port. The bind address and port are logged at startup. +With `--ipc`, `--host` requires an explicit `--port`; `--cftunnel` is not supported. + ## Connect to Open WebUI 1. Open **Settings → Admin → Integrations → Open Terminal**. diff --git a/assets/home.webp b/assets/home.webp new file mode 100644 index 0000000..3c30e2a Binary files /dev/null and b/assets/home.webp differ diff --git a/open_terminal/cli.py b/open_terminal/cli.py index 936049f..c7d6d7d 100644 --- a/open_terminal/cli.py +++ b/open_terminal/cli.py @@ -23,8 +23,9 @@ BANNER = r""" @main.command() -@click.option("--host", default=None, help="Bind host (default: 127.0.0.1 with --cftunnel, otherwise 0.0.0.0)") -@click.option("--port", default=None, type=int, help="Bind port (default: 8000)") +@click.option("--host", default=None, help="Bind host (default: 127.0.0.1 with --ipc or --cftunnel, otherwise 0.0.0.0)") +@click.option("--port", default=None, type=click.IntRange(0, 65535), help="Bind port (default: 8000; with --ipc, explicitly enables TCP)") +@click.option("--ipc", default=None, help="Serve over a Unix socket or Windows named pipe instead of TCP.") @click.option( "--config", "config_path", @@ -66,6 +67,7 @@ def run( cftunnel: bool, yes: bool, isolated: bool, + ipc: str | None, ): """Start the sandbox API server.""" import secrets @@ -75,12 +77,21 @@ def run( if yes and not cftunnel: raise click.UsageError("--yes requires --cftunnel.") + if ipc and cftunnel: + raise click.UsageError("--ipc cannot be combined with --cftunnel.") + if ipc and host is not None and port is None: + raise click.UsageError("--host requires --port when using --ipc.") + if ipc and os.name == "nt" and not ipc.startswith("\\\\.\\pipe\\"): + raise click.UsageError("--ipc must be a local Windows named pipe path.") + if ipc and os.name != "nt" and not os.path.isabs(ipc): + raise click.UsageError("--ipc must be an absolute Unix socket path.") # Load config files before resolving other settings. cfg = config.init(config_path, isolated=isolated) # Resolve host/port: CLI flag > config file > built-in default - host = host or cfg.get("host", "127.0.0.1" if cftunnel else "0.0.0.0") + ipc_port = port # Only an explicit --port opts IPC mode into TCP listening. + host = host or ("127.0.0.1" if ipc else cfg.get("host", "127.0.0.1" if cftunnel else "0.0.0.0")) port = port if port is not None else cfg.get("port", 8000) if cftunnel and (type(port) is not int or not 1 <= port <= 65535): raise click.UsageError("--cftunnel requires a port between 1 and 65535.") @@ -129,8 +140,8 @@ def run( if cftunnel: local_url = origin_url(host, port) - click.echo(f" {click.style('Local:', bold=True)} {click.style(local_url, fg='cyan')}") - if host == "0.0.0.0": + click.echo(f" {click.style('Local:', bold=True)} {click.style('IPC: ' + ipc if ipc else local_url, fg='cyan')}") + if not ipc and host == "0.0.0.0": import socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -146,7 +157,7 @@ def run( click.echo(f" {click.style('API Key:', bold=True)} {api_key}") click.echo() - if host in ("0.0.0.0", "::"): + if not ipc and host in ("0.0.0.0", "::"): click.echo(click.style(" Warning: Listening on all network interfaces.", fg="yellow")) click.echo(click.style(" Use --host 127.0.0.1 to restrict to this machine.", dim=True)) click.echo() @@ -166,6 +177,10 @@ def run( uvicorn_options = {} if UVICORN_TIMEOUT_KEEP_ALIVE is not None: uvicorn_options["timeout_keep_alive"] = UVICORN_TIMEOUT_KEEP_ALIVE + if ipc: + from open_terminal.ipc import run_server as run_ipc_server + run_ipc_server(ipc, ipc_port, host, **uvicorn_options) + return if cftunnel: run_server(binary, host, port, loop=UVICORN_LOOP, **uvicorn_options) return diff --git a/open_terminal/ipc.py b/open_terminal/ipc.py new file mode 100644 index 0000000..0bd276f --- /dev/null +++ b/open_terminal/ipc.py @@ -0,0 +1,85 @@ +"""Serve the existing ASGI API over local IPC, optionally also on TCP.""" + +import asyncio +import logging +import os +import sys + +import uvicorn + + +class _PipeListener: + # asyncio's Windows PipeServer closes synchronously and has no wait_closed. + def __init__(self, server): + self.server = server + + def close(self): + self.server.close() + + async def wait_closed(self): + pass + + +class IPCServer(uvicorn.Server): + def __init__(self, config, path, http_port=None, http_host="127.0.0.1"): + super().__init__(config) + self.path = path + self.http_port = http_port + self.http_host = http_host + self.bound_path = False + + async def startup(self, sockets=None): + # Let Uvicorn own ASGI lifespan and shutdown, without opening a TCP socket. + await super().startup(sockets=[]) + self.started = False + if self.should_exit: + return + loop = asyncio.get_running_loop() + + def protocol(): + return self.config.http_protocol_class( + config=self.config, + server_state=self.server_state, + app_state=self.lifespan.state, + ) + + try: + if sys.platform == "win32": + pipes = await loop.start_serving_pipe(protocol, self.path) + self.servers.extend(_PipeListener(pipe) for pipe in pipes) + else: + # Never replace another process's socket (including a stale one). + if os.path.lexists(self.path): + raise FileExistsError(self.path) + server = await loop.create_unix_server(protocol, path=self.path) + self.servers.append(server) + self.bound_path = True + os.chmod(self.path, 0o600) + if self.http_port is not None: + server = await loop.create_server(protocol, self.http_host, self.http_port) + self.servers.append(server) + port = server.sockets[0].getsockname()[1] + logging.getLogger("uvicorn.error").info("HTTP: http://%s:%s", self.http_host, port) + self.started = True + except BaseException: + await self.shutdown() + raise + + async def shutdown(self, sockets=None): + try: + await super().shutdown(sockets=sockets) + finally: + if self.bound_path: + self.bound_path = False + try: + os.unlink(self.path) + except FileNotFoundError: + pass + + +def run_server(path, http_port=None, http_host="127.0.0.1", **options): + # Proactor is required for named pipes and subprocesses on Windows. + # asyncio.run uses it by default; bypass Uvicorn's optional loop selection. + config = uvicorn.Config("open_terminal.main:app", loop="asyncio", **options) + server = IPCServer(config, path, http_port, http_host) + asyncio.run(server.serve())