Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
"""Shared-secret authentication and bind-address helpers for the human tool.
Stdlib only, so the adapter can use it without the server or UI extras.
The human tool decides whether an agent may go ahead with an action, so only
the person running it (and the agent they start) may talk to it. Every API
route needs ``Authorization: Bearer <token>``.
Where the token comes from:
* ``CUA_HUMAN_TOOL_TOKEN`` if it is set. Use this to share the token with a
client on another machine, or to pick your own.
* Otherwise the server makes a random token each time it starts and writes it
to ``$CUA_HOME/human_tool/token`` (default ``~/.cua/human_tool/token``) with
owner-only permissions. The adapter and the Gradio UI on the same machine
read that file, so nothing needs to be configured.
The server listens on 127.0.0.1 unless you pass ``--host`` or set
``CUA_HUMAN_TOOL_HOST``.
"""
import hmac
import os
import secrets
import sys
from pathlib import Path
from typing import Callable, Optional
TOKEN_ENV = "CUA_HUMAN_TOOL_TOKEN"
HOST_ENV = "CUA_HUMAN_TOOL_HOST"
DEFAULT_HOST = "127.0.0.1"
# Token generated by this process, cached so every request sees the same one.
_generated_token: Optional[str] = None
def token_file() -> Path:
"""Where a generated token is stored (``$CUA_HOME`` else ``~/.cua``)."""
base = os.environ.get("CUA_HOME") or ""
root = Path(base) if base else Path.home() / ".cua"
return root / "human_tool" / "token"
def resolve_host(host: Optional[str] = None) -> str:
"""Address to listen on: explicit value, else ``CUA_HUMAN_TOOL_HOST``, else loopback."""
return host or os.environ.get(HOST_ENV) or DEFAULT_HOST
def is_loopback(host: str) -> bool:
return host in ("127.0.0.1", "localhost", "::1")
def _write_private(path: Path, value: str) -> None:
"""Write ``value`` to ``path`` readable by the current user only."""
path.parent.mkdir(parents=True, exist_ok=True)
try:
os.chmod(path.parent, 0o700)
except OSError:
pass
# Drop any older file first so the new one is created with 0600 from the start.
try:
path.unlink()
except FileNotFoundError:
pass
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w") as fh:
fh.write(value)
def server_token() -> str:
"""Token the server expects. Generates and stores one the first time if needed."""
global _generated_token
env_token = os.environ.get(TOKEN_ENV)
if env_token:
return env_token
if _generated_token is None:
token = secrets.token_urlsafe(32)
_write_private(token_file(), token)
_generated_token = token
return _generated_token
def client_token(explicit: Optional[str] = None) -> Optional[str]:
"""Token a client should send: explicit value, else env var, else the token file."""
if explicit:
return explicit
env_token = os.environ.get(TOKEN_ENV)
if env_token:
return env_token
try:
return token_file().read_text().strip() or None
except OSError:
return None
def auth_headers(explicit: Optional[str] = None) -> dict:
"""Headers carrying the bearer token, or an empty dict if none is known."""
token = client_token(explicit)
return {"Authorization": f"Bearer {token}"} if token else {}
def token_matches(candidate: Optional[str], expected: str) -> bool:
"""Constant-time comparison."""
if not candidate:
return False
return hmac.compare_digest(candidate.encode("utf-8"), expected.encode("utf-8"))
def gradio_auth(get_token: Callable[[], Optional[str]]):
"""Login check for the Gradio page: any username, the token as the password.
Without it, anyone who can open the page could answer approvals, because
the page calls the API with the token itself.
"""
def check(username: str, password: str) -> bool:
token = get_token()
return bool(token) and token_matches(password, token)
return check
def announce(host: str, port: int) -> None:
"""Tell the operator where the token lives (never the token itself)."""
if os.environ.get(TOKEN_ENV):
print(f"Auth: using the token from ${TOKEN_ENV}", file=sys.stderr)
else:
print(f"Auth: token saved to {token_file()}", file=sys.stderr)
print(
f" to use a client on another machine, set ${TOKEN_ENV} on both sides",
file=sys.stderr,
)
if not is_loopback(host):
print(
f"WARNING: listening on {host}:{port}, reachable from other machines. "
"Anyone with the token can approve agent actions.",
file=sys.stderr,
)