Skip to content
Python

Remote machines: identity, reverse channel, acceptor, sealed key wallet

Rohit C Prasad274c9a582bd4
diff --git a/coworker/audit.py b/coworker/audit.py
index 5199a7b7..88e18e17 100644
--- a/coworker/audit.py
+++ b/coworker/audit.py
@@ -67,6 +67,10 @@ class AuditStore:
# layer further out.
("cache_read", "INTEGER DEFAULT 0"),
("cache_write", "INTEGER DEFAULT 0"),
+ # Fleet under the org (2026-09-02): the verified login behind the session
+ # this call ran in — "" for local/desktop or automated sessions.
+ ("actor", "TEXT DEFAULT ''"),
+ ("approved_by", "TEXT DEFAULT ''"),
):
try:
self._conn.execute(
@@ -75,6 +79,29 @@ class AuditStore:
except sqlite3.OperationalError:
pass # column already exists
self._conn.commit()
+ # Export hooks (remote/audit_export.py): told after every commit, outside the
+ # lock, with the row's id — the emitter reads the row back by cursor.
+ self._listeners: list[Any] = []
+
+ def subscribe(self, callback) -> None:
+ self._listeners.append(callback)
+
+ def list_since(self, after_id: int, *, limit: int = 200) -> list[dict[str, Any]]:
+ """Rows with id > after_id, OLDEST first — the export cursor's read."""
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT * FROM audit_events WHERE id > ? ORDER BY id ASC LIMIT ?",
+ (int(after_id), max(1, min(int(limit or 200), 1000))),
+ ).fetchall()
+ out = []
+ for row in rows:
+ item = dict(row)
+ try:
+ item["args"] = json.loads(item.get("args") or "{}")
+ except json.JSONDecodeError:
+ item["args"] = {}
+ out.append(item)
+ return out
def append(self, event: dict[str, Any]) -> None:
tool = str(event.get("tool") or event.get("tool_name") or "")
@@ -87,8 +114,8 @@ class AuditStore:
self._conn.execute(
"""
INSERT INTO audit_events
- (session_id, agent, workspace, connector, tool, stage, status, approval, args, result_preview, reason, resource, call_id, tokens_in, tokens_out, cache_read, cache_write)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ (session_id, agent, workspace, connector, tool, stage, status, approval, args, result_preview, reason, resource, call_id, tokens_in, tokens_out, cache_read, cache_write, actor, approved_by)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
event.get("session_id") or "",
@@ -108,9 +135,17 @@ class AuditStore:
int(event.get("tokens_out") or 0),
int(event.get("cache_read") or 0),
int(event.get("cache_write") or 0),
+ str(event.get("actor") or ""),
+ str(event.get("approved_by") or ""),
),
)
self._conn.commit()
+ row_id = self._conn.execute("SELECT last_insert_rowid()").fetchone()[0]
+ for cb in list(self._listeners):
+ try:
+ cb(row_id)
+ except Exception:
+ pass # an export hook must never break the audited action
def reviewer_stats(self, session_id: str) -> dict[str, Any]:
"""Per-session Auto-Approve metering (§1.7), computed from the durable rows so it
diff --git a/coworker/basedir.py b/coworker/basedir.py
new file mode 100644
index 00000000..16839243
--- /dev/null
+++ b/coworker/basedir.py
@@ -0,0 +1,44 @@
+"""OPENWORKER_BASE_DIR — one directory the box never looks beyond.
+
+Owner ruling 2026-09-02 (spec §Fly sandboxes, "Base directory"): when the
+variable is set, the state dir, every scratch workspace, and every folder a
+user adds — typed remote paths, save-as-project targets, extra roots — must
+resolve UNDER it; anything outside is refused with a plain error. On a
+managed sandbox it is the volume mount (/data). On a machine the user
+brought it is optional; unset means today's behaviour, no restriction.
+
+This is the path discipline. The tool-level sandbox that later makes
+"nothing beyond base" mechanical (sandbox-refactor-design.md) then changes a
+mechanism, not what users see.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Optional
+
+
+class OutsideBaseDir(ValueError):
+ """A path outside OPENWORKER_BASE_DIR on a box that has one."""
+
+
+def base_dir() -> Optional[Path]:
+ raw = os.environ.get("OPENWORKER_BASE_DIR", "").strip()
+ return Path(raw).expanduser() if raw else None
+
+
+def ensure_under_base(path: str | os.PathLike, what: str = "folder") -> Path:
+ """Expand and resolve `path`; raise OutsideBaseDir when a base is set and
+ the path is not inside it. Symlinks are resolved first so a link out of
+ the base does not slip through. Returns the resolved path either way."""
+ resolved = Path(path).expanduser().resolve()
+ base = base_dir()
+ if base is None:
+ return resolved
+ root = base.resolve()
+ if resolved != root and not resolved.is_relative_to(root):
+ raise OutsideBaseDir(
+ f"this machine only works under {root} — pick a {what} inside it"
+ )
+ return resolved
diff --git a/coworker/cli.py b/coworker/cli.py
index 88e6d069..f73fc68d 100644
--- a/coworker/cli.py
+++ b/coworker/cli.py
@@ -15,7 +15,20 @@ from .permissions import Mode
from .secrets import state_dir
+REMOTE_COMMANDS = ("join", "auth", "up", "status", "leave", "secrets", "service")
+
+
def main(argv: Optional[list[str]] = None) -> None:
+ import sys
+
+ # Remote-home verbs run headless (no TUI) and must win over the positional
+ # `skill` argument — `openworker join <url>` is a command, not a skill.
+ args = sys.argv[1:] if argv is None else argv
+ if args and args[0] in REMOTE_COMMANDS:
+ from .remote.joiner import cli as remote_cli
+
+ raise SystemExit(remote_cli(args))
+
cfg = load_config()
parser = argparse.ArgumentParser(
prog="openworker", description="Agent coworker (TUI)."
diff --git a/coworker/cloud.py b/coworker/cloud.py
index 3850de5e..8e1b5e92 100644
--- a/coworker/cloud.py
+++ b/coworker/cloud.py
@@ -56,7 +56,9 @@ PROVIDER_FOR_CONNECTOR = {
# outlives the sidecar process simply has to be restarted.
_pending_logins: dict[str, dict[str, float | str]] = {}
_PENDING_TTL = 600
-_pending_managed_states: dict[str, float] = {}
+# Each pending managed connect records when it started and (optionally) which
+# machine the grant is destined for — the callback routes on that record.
+_pending_managed_states: dict[str, dict[str, Any]] = {}
_MANAGED_STATE_TTL = 600
@@ -349,6 +351,8 @@ def begin_managed_connect(
*,
access: str = "",
flow: str = "",
+ machine_id: str = "",
+ machine_name: str = "",
) -> dict[str, Any]:
"""Authenticated start: returns the provider consent URL for the browser.
Requires sign-in — the manual token path stays available regardless.
@@ -384,7 +388,13 @@ def begin_managed_connect(
return {"ok": False, "error": f"cloud unreachable: {type(exc).__name__}"}
if resp.status_code != 200:
return {"ok": False, "error": f"start failed ({resp.status_code})"}
- _pending_managed_states[app_state] = _now()
+ _pending_managed_states[app_state] = {
+ "created": _now(),
+ # A machine-targeted connect (machines spec §Remote OAuth): the callback
+ # ships the grant to this machine instead of storing it locally.
+ "machine_id": machine_id,
+ "machine_name": machine_name,
+ }
return {
"ok": True,
"authorize_url": resp.json()["authorize_url"],
@@ -392,12 +402,18 @@ def begin_managed_connect(
}
-def consume_managed_state(state: str) -> bool:
- """Consume one recent managed-OAuth callback state exactly once."""
+def consume_managed_state(state: str) -> Optional[dict[str, Any]]:
+ """Consume one recent managed-OAuth callback state exactly once.
+
+ Returns the pending record ({"machine_id": …, "machine_name": …}) so the
+ callback can route a machine-targeted grant, or None for an unknown or
+ expired state."""
if not state:
- return False
- created = _pending_managed_states.pop(state, None)
- return created is not None and created >= _now() - _MANAGED_STATE_TTL
+ return None
+ record = _pending_managed_states.pop(state, None)
+ if record is None or record["created"] < _now() - _MANAGED_STATE_TTL:
+ return None
+ return record
def managed_profile_from_callback(form: dict[str, str]) -> dict[str, Any]:
@@ -427,6 +443,56 @@ def managed_profile_from_callback(form: dict[str, str]) -> dict[str, Any]:
return profile
+def delegate_connection(
+ secrets: SecretStore,
+ config: Config,
+ connection_id: str,
+ *,
+ seal_pubkey: str = "",
+ machine_id: str = "",
+) -> Optional[dict[str, str]]:
+ """Handoff step (machines spec §Remote OAuth): mark a managed connection
+ machine-held at the broker, so the machine can renew it by possession.
+
+ Returns {"user_id": …, "machine_credential": …} — both travel with the
+ grant. The credential arrives only when `seal_pubkey` (the machine's
+ pinned sealing key) is sent: the broker then mints the connection-scoped
+ secret that authenticates the machine's event polling (spec §Managed
+ events) and switches the connection's relay events to that machine's
+ sealed queue. `machine_id` (spec §Fly sandboxes) names the holding
+ machine as the hosted control plane knows it, so the broker can wake a
+ sleeping sandbox after queueing an event; only hosted (`cloud:`) rows
+ have one. None = not delegated."""
+ token = fresh_access_token(secrets, config)
+ if not token:
+ return None
+ body: dict[str, str] = {}
+ if seal_pubkey:
+ body["seal_pubkey"] = seal_pubkey
+ if machine_id:
+ body["machine_id"] = machine_id
+ try:
+ resp = httpx.post(
+ config.cloud_base_url.rstrip("/")
+ + f"/v1/connections/{connection_id}/delegate",
+ headers={"Authorization": f"Bearer {token}"},
+ **({"json": body} if body else {}),
+ timeout=20,
+ )
+ except httpx.HTTPError:
+ return None
+ if resp.status_code != 200:
+ return None
+ body = resp.json()
+ user_id = str(body.get("user_id") or "")
+ if not user_id:
+ return None
+ return {
+ "user_id": user_id,
+ "machine_credential": str(body.get("machine_credential") or ""),
+ }
+
+
def refresh_managed_token(
secrets: SecretStore,
config: Config,
@@ -443,20 +509,39 @@ def refresh_managed_token(
if not (profile.get("managed") and profile.get("refresh_token")):
return None
provider = profile.get("provider") or PROVIDER_FOR_CONNECTOR.get(connector)
- token = fresh_access_token(secrets, config)
- if not provider or not token:
+ if not provider:
return None
- try:
- resp = httpx.post(
- config.cloud_base_url.rstrip("/") + f"/v1/oauth/{provider}/refresh",
- json={
- "refresh_token": profile["refresh_token"],
- "connection_id": profile.get("connection_id", ""),
- "connector": connector,
- },
- headers={"Authorization": f"Bearer {token}"},
- timeout=20,
+ token = fresh_access_token(secrets, config)
+ if token:
+ url = config.cloud_base_url.rstrip("/") + f"/v1/oauth/{provider}/refresh"
+ headers = {"Authorization": f"Bearer {token}"}
+ body = {
+ "refresh_token": profile["refresh_token"],
+ "connection_id": profile.get("connection_id", ""),
+ "connector": connector,
+ }
+ else:
+ # Machine-held grant (machines spec §Remote OAuth): no cloud session
+ # here — renew by possession against the delegated route. Works only
+ # for grants a signed-in user delegated at handoff; the broker's
+ # guardrails (pacing, uniform 401s, failure auto-suspend) apply.
+ user_id = str(profile.get("broker_user_id") or "")
+ connection_id = str(profile.get("connection_id") or "")
+ if not (user_id and connection_id):
+ return None
+ url = (
+ config.cloud_base_url.rstrip("/")
+ + f"/v1/oauth/{provider}/refresh-delegated"
)
+ headers = {}
+ body = {
+ "refresh_token": profile["refresh_token"],
+ "connection_id": connection_id,
+ "user_id": user_id,
+ "connector": connector,
+ }
+ try:
+ resp = httpx.post(url, json=body, headers=headers, timeout=20)
except httpx.HTTPError:
return None
if resp.status_code != 200:
@@ -490,6 +575,48 @@ def ensure_fresh_connector_token(
refresh_managed_token(secrets, config, connector, profile_key=profile_key)
+def revoke_connector_connections(
+ secrets: SecretStore, config: Config, connector: str
+) -> int:
+ """Revoke every live broker connection for a connector, by NAME.
+
+ The machine-held case (machines spec §Managed events, drill finding): a
+ box's own disconnect deletes its copy but cannot reach the broker (no
+ session — by design), which would leave the delegation lingering and the
+ connection's events black-holed. The DESKTOP holds the session, so it
+ performs the revocation — without needing any local profile (the desktop
+ forgot the grant at handoff). Returns how many connections were revoked."""
+ token = fresh_access_token(secrets, config)
+ if not token:
+ return 0
+ base = config.cloud_base_url.rstrip("/")
+ try:
+ resp = httpx.get(
+ base + "/v1/connections",
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=15,
+ )
+ except httpx.HTTPError:
+ return 0
+ if resp.status_code != 200:
+ return 0
+ revoked = 0
+ for row in resp.json().get("connections", []):
+ if row.get("connector") != connector or row.get("status") == "disconnected":
+ continue
+ try:
+ r = httpx.post(
+ base + f"/v1/connections/{row['connection_id']}/disconnect",
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=10,
+ )
+ except httpx.HTTPError:
+ continue
+ if r.status_code == 200:
+ revoked += 1
+ return revoked
+
+
def cloud_disconnect(
secrets: SecretStore,
config: Config,
@@ -539,15 +666,31 @@ def github_installation_token(
if cached and cached[1] > _now() + _GITHUB_TOKEN_LEEWAY:
return cached[0]
token = fresh_access_token(secrets, config)
- if not token:
- return ""
+ if token:
+ url = config.cloud_base_url.rstrip("/") + "/v1/github/token"
+ payload: dict[str, str] = {"installation_id": installation_id}
+ headers = {"Authorization": f"Bearer {token}"}
+ else:
+ # Machine-held GitHub (machines spec §Managed events, increment 2):
+ # a box has no cloud session — it mints by machine credential on the
+ # delegated route, using the stamps the handoff wrote to the pointer.
+ pointer = secrets.get("github:default") or {}
+ credential = str(pointer.get("machine_credential") or "")
+ if not (
+ credential
+ and pointer.get("connection_id")
+ and pointer.get("broker_user_id")
+ ):
+ return ""
+ url = config.cloud_base_url.rstrip("/") + "/v1/machine/github/mint"
+ payload = {
+ "installation_id": installation_id,
+ "connection_id": str(pointer["connection_id"]),
+ "user_id": str(pointer["broker_user_id"]),
+ }
+ headers = {"Authorization": f"Bearer {credential}"}
try:
- resp = httpx.post(
- config.cloud_base_url.rstrip("/") + "/v1/github/token",
- json={"installation_id": installation_id},
- headers={"Authorization": f"Bearer {token}"},
- timeout=20,
- )
+ resp = httpx.post(url, json=payload, headers=headers, timeout=20)
except httpx.HTTPError:
return ""
if resp.status_code != 200:
@@ -687,3 +830,30 @@ def gallery_detail(secrets: SecretStore, config: Config, slug: str) -> Optional[
"capabilities": capabilities,
"recommends": recommends,
}
+
+
+def broker_request(
+ secrets: SecretStore,
+ config: Config,
+ method: str,
+ path: str,
+ body: Optional[dict[str, Any]] = None,
+) -> tuple[int, Any]:
+ """One user-authed call to the broker for the desktop GUI's cloud views
+ (UX-049 4c). Returns (status, json); (401, …) when signed out; (0, …)
+ when unreachable. The token stays in this process."""
+ token = fresh_access_token(secrets, config)
+ if not token:
+ return 401, {"error": "not signed in"}
+ url = config.cloud_base_url.rstrip("/") + path
+ try:
+ resp = httpx.request(
+ method, url, json=body, headers={"Authorization": f"Bearer {token}"}, timeout=20
+ )
+ except httpx.HTTPError:
+ return 0, {"error": "cloud unreachable"}
+ try:
+ data = resp.json()
+ except ValueError:
+ data = {"error": resp.text[:200]}
+ return resp.status_code, data
diff --git a/coworker/remote/__init__.py b/coworker/remote/__init__.py
new file mode 100644
index 00000000..9809e8aa
--- /dev/null
+++ b/coworker/remote/__init__.py
@@ -0,0 +1,10 @@
+"""Remote homes — headless workers that dial OUT and join a controller.
+
+One codebase, two composable roles (remote-home-design.md):
+ - WORKER: the entire existing server (state, engines, ASGI app) with NO
+ listener — `joiner.py` dials out and the held WebSocket carries a small
+ RPC framing into the app in-process.
+ - ACCEPTOR: a thin module (enrollment, machines registry, socket holder,
+ proxy prefix) mounted into the sidecar app — and nothing else, so the
+ future cloud service is "import acceptor, add auth".
+"""
diff --git a/coworker/remote/acceptor.py b/coworker/remote/acceptor.py
new file mode 100644
index 00000000..624fe6f1
--- /dev/null
+++ b/coworker/remote/acceptor.py
@@ -0,0 +1,1315 @@
+"""Join-acceptor: the controller half of remote homes, as one mountable module.
+
+Deliberately self-contained (remote-home-design.md, owner ruling 2026-08-24):
+the desktop sidecar mounts this next to its own routes; the future cloud
+service imports THIS module and adds multi-tenant auth — never an extraction
+project. It owns:
+
+ - arming + single-use enrollment tokens (10-minute TTL, in-memory: a
+ restart disarms, which is the safe default),
+ - the machines registry (durable) and the live socket map (presence),
+ - the `/ws/machine` endpoint (hello → challenge → auth → welcome),
+ - the proxy prefix `/v1/machines/{mid}/p/<path>` that makes a remote home
+ literally "a different base URL" for the GUI.
+
+Auth model: the REST surface rides the sidecar-token middleware like every
+other /v1 route (GUI-only). The machine WebSocket is the one surface remote
+boxes reach, and it authenticates with the enrollment token (first contact)
+or an ed25519 challenge-response (every reconnect) — never the sidecar token,
+which must not leave this machine.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+import re
+import secrets as pysecrets
+import time
+from typing import Any, Optional
+
+from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
+from fastapi.responses import JSONResponse, PlainTextResponse, Response
+
+from . import channel as ch
+from .audit import AuditLog, NullAuditLog
+from .identity import seal_b64, verify_b64, verify_seal_attestation
+from .provision import LocalProvisioner, Provisioner
+from .stores import Ephemera, InMemoryEphemera, Registry
+
+TOKEN_TTL_SECONDS = 600.0
+_CHALLENGE_BYTES = 32
+
+# Device-authorization flow (`openworker auth join`): the box asks, the user
+# approves in the controller UI, approval mints the one join token.
+DEVICE_TTL_SECONDS = 900.0
+DEVICE_POLL_SECONDS = 5
+# TTL-leased Ephemera backends (Redis) get a heartbeat from each live machine
+# connection, so a crashed acceptor node frees its identities by expiry.
+LEASE_REFRESH_SECONDS = 30.0
+# No lookalike characters — the user reads this code off a terminal.
+_USER_CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
+
+# The one proxied path whose successful responses feed the transcript cache.
+_TRANSCRIPT_PATH = re.compile(r"v1/sessions/([^/]+)/messages")
+# How long a proxied call waits for a just-woken sandbox to dial back in.
+WAKE_WAIT_SECONDS = 45.0
+
+# Proxied hops must not forward controller-side auth or hop-by-hop headers.
+_PROXY_SKIP_RESPONSE_HEADERS = {
+ "content-length",
+ "transfer-encoding",
+ "connection",
+ "content-encoding",
+}
+
+
+class _LiveMachine:
+ def __init__(self, machine_id: str, name: str, rpc: ch.RpcClient) -> None:
+ self.machine_id = machine_id
+ self.name = name
+ self.rpc = rpc
+ self.connected_at = time.time()
+ # Bridged WebSocket streams: stream id -> the GUI-facing socket.
+ self.streams: dict[str, WebSocket] = {}
+ self.stream_counter = 0
+
+
+class RemoteAcceptor:
+ def __init__(self, registry: Registry, ephemera: Optional[Ephemera] = None) -> None:
+ self.registry = registry
+ self.ephemera: Ephemera = ephemera or InMemoryEphemera()
+ self._live: dict[str, _LiveMachine] = {} # machine_id -> live channel
+
+ # -- arming ---------------------------------------------------------------
+ def arm(
+ self,
+ bound_fingerprint: str = "",
+ org_id: str = "",
+ actor: str = "",
+ provenance: Optional[dict[str, str]] = None,
+ ) -> tuple[str, float]:
+ """Mint one single-use enrollment token; arming is per-token, not a
+ mode. A bound token enrolls only the machine identity it was approved
+ for (the device flow binds; the Add-a-machine card does not). The
+ token carries the org the enrollment lands in — that is how a brand-new
+ machine inherits its tenant — and, for a managed sandbox, the
+ provenance {"kind", "ref"} stamped on the row it enrolls."""
+ token = pysecrets.token_urlsafe(24)
+ expiry = time.time() + TOKEN_TTL_SECONDS
+ self.ephemera.add_token(token, expiry, bound_fingerprint, org_id, actor, provenance)
+ return token, expiry
+
+ def disarm(self) -> None:
+ self.ephemera.clear_tokens()
+
+ def consume_token(self, token: str) -> Optional[dict[str, Any]]:
+ """None = invalid/expired; else {"fingerprint": binding or "", "org_id": …}."""
+ return self.ephemera.consume_token(token)
+
+ @property
+ def armed(self) -> bool:
+ return self.ephemera.has_tokens()
+
+ # -- presence -------------------------------------------------------------
+ def live(self, machine_id: str) -> Optional[_LiveMachine]:
+ return self._live.get(machine_id)
+
+ def machines(self, org_id: Optional[str] = None) -> list[dict[str, Any]]:
+ rows = []
+ for row in self.registry.list(org_id):
+ live = self._live.get(row["id"])
+ rows.append(
+ {
+ "id": row["id"],
+ "name": row["name"],
+ "fingerprint": _fingerprint(row["pubkey"]),
+ "app_version": row.get("app_version") or "",
+ # Fleet under the org: who armed/approved the enrollment.
+ "enrolled_by": row.get("enrolled_by") or "",
+ # "" = the user's own machine; "fly" = a managed sandbox
+ # (spec §Fly sandboxes) — the dashboard shows the difference.
+ "provenance": row.get("provenance") or "",
+ "provenance_ref": row.get("provenance_ref") or "",
+ "created_at": row["created_at"],
+ "last_seen": row["last_seen"],
+ "connected": live is not None,
+ # Public halves only. The sealing key lets a BROWSER seal
+ # deploys to this machine (OPE-149); its fingerprint is
+ # what the user checks against `openworker status`.
+ "seal_pubkey": row.get("seal_pubkey") or "",
+ "seal_fingerprint": (
+ _fingerprint(row["seal_pubkey"])
+ if row.get("seal_pubkey")
+ else ""
+ ),
+ }
+ )
+ return rows
+
+ def attach(self, machine_id: str, name: str, pubkey: str, rpc: ch.RpcClient) -> None:
+ """Caller holds the clone-trap lease for pubkey (acquired pre-enroll)."""
+ self._live[machine_id] = _LiveMachine(machine_id, name, rpc)
+
+ async def push_policy(self, machine_id: str, policy: dict[str, Any]) -> tuple[int, dict[str, Any]]:
+ """Hand a live machine its (changed) org policy; (status, body) from the
+ box. Offline machines get it on their next welcome."""
+ live = self.live(machine_id)
+ if live is None:
+ return 503, {"error": "machine offline"}
+ status, body, _ = await live.rpc.request_frame({"type": "policy", "policy": policy})
+ try:
+ parsed = json.loads(body.decode() or "{}")
+ except (ValueError, AttributeError):
+ parsed = {}
+ return status, parsed
+
+ async def detach(self, machine_id: str, pubkey: str) -> None:
+ live = self._live.pop(machine_id, None)
+ self.ephemera.release_lease(pubkey)
+ if live is not None:
+ live.rpc.close()
+ for gui_ws in list(live.streams.values()):
+ try:
+ await gui_ws.close(code=1001) # machine went away
+ except Exception:
+ pass
+ live.streams.clear()
+ self.registry.touch(machine_id)
+
+
+def _fingerprint(pubkey_b64: str) -> str:
+ import base64
+ import hashlib
+
+ try:
+ raw = base64.b64decode(pubkey_b64.encode("ascii"))
+ except Exception:
+ return ""
+ return hashlib.sha256(raw).hexdigest()[:16]
+
+
+def mount_acceptor(
+ app: FastAPI,
+ registry: Registry,
+ *,
+ ws_authenticated=None,
+ origin_allowed=None,
+ api_token: str = "",
+ wallet=None,
+ ephemera: Optional[Ephemera] = None,
+ provisioner: Optional[Provisioner] = None,
+ audit: Optional[AuditLog] = None,
+ tenant_resolver=None,
+ deploy_allowed=None,
+ approval_url: str = "",
+ policy_for=None,
+ audit_sink=None,
+ policy_status=None,
+ machine_activity=None,
+ machine_wake=None,
+) -> RemoteAcceptor:
+ """`ws_authenticated` is the sidecar's GUI WebSocket auth check — passed in
+ because it lives in create_app's closure and guards the GUI-facing bridged
+ socket exactly like /ws/session. The machine-facing socket never uses it.
+ `wallet` is the desktop's SecretStore — the keys wallet the deploy
+ endpoints read from (values resolved server-side; the GUI sends NAMES).
+ `registry`/`ephemera` are the control-plane stores (stores.py) — desktop
+ passes SQLite/nothing, cloud passes Postgres/Redis implementations.
+
+ `tenant_resolver` makes the mount multi-tenant: called with the incoming
+ Request (or the GUI-facing WebSocket) it returns {"org_id": …, "actor": …}
+ for an authenticated caller or None (→ 401). Every control-plane endpoint
+ is then row-scoped to the caller's org, tokens carry the org so machines
+ enroll into it, and the pending-grants LISTING disappears (approval is by
+ typed code only — a listing would show other tenants' machines). Omitted
+ (the desktop), everything runs in the single org ""."""
+ acceptor = RemoteAcceptor(registry, ephemera)
+ app.state.remote_acceptor = acceptor
+ provisioner = provisioner or LocalProvisioner(acceptor)
+
+ # Managed sandboxes (spec §Fly sandboxes, lifecycle): `machine_activity(
+ # machine_id)` is told about every proxied call and bridged socket so the
+ # control plane can idle-stop a sandbox nobody is using; `machine_wake(
+ # machine_id) -> bool` is asked when a caller reaches an OFFLINE machine —
+ # True means "it is a sandbox and I started it", and the proxy then waits
+ # for the box to dial back in before answering. Desktop passes neither.
+ def _touch(machine_id: str) -> None:
+ if machine_activity is not None:
+ try:
+ machine_activity(machine_id)
+ except Exception:
+ pass
+
+ async def _live_or_wake(machine_id: str):
+ live = acceptor.live(machine_id)
+ if live is not None or machine_wake is None:
+ return live
+ try:
+ woke = await machine_wake(machine_id)
+ except Exception:
+ woke = False
+ if not woke:
+ return None
+ deadline = time.monotonic() + WAKE_WAIT_SECONDS
+ while time.monotonic() < deadline:
+ live = acceptor.live(machine_id)
+ if live is not None:
+ return live
+ await asyncio.sleep(0.5)
+ return None
+ audit = audit or NullAuditLog()
+ multi_tenant = tenant_resolver is not None
+ _desktop_tenant = {"org_id": "", "actor": ""}
+
+ async def _tenant(conn) -> Optional[dict[str, Any]]:
+ """Resolve the caller's tenant from a Request or WebSocket; None = 401.
+ The resolver may be sync or async (a hosted one awaits its IdP)."""
+ if tenant_resolver is None:
+ return _desktop_tenant
+ result = tenant_resolver(conn)
+ if inspect.isawaitable(result):
+ result = await result
+ return result
+
+ _unauthorized = JSONResponse({"error": "unauthorized"}, status_code=401)
+
+ def _org_machine(machine_id: str, tenant: dict[str, Any]):
+ """Fetch a machine the caller is allowed to touch, or None. A row in
+ another org is a 404, indistinguishable from not existing at all."""
+ row = registry.by_id(machine_id)
+ if row is None or (row.get("org_id") or "") != tenant["org_id"]:
+ return None
+ return row
+
+ @app.get("/j/{token}")
+ async def join_hint(token: str) -> PlainTextResponse:
+ # Informational only, and deliberately constant: it must not confirm
+ # whether a token is valid to an unauthenticated caller.
+ return PlainTextResponse(
+ "This is an OpenWorker join URL. On the machine you want to add, run:\n"
+ " openworker join <this URL> [--name=my-box]\n"
+ )
+
+ @app.post("/v1/remote/arm")
+ async def arm(request: Request) -> Any:
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ token, expiry = acceptor.arm(org_id=tenant["org_id"], actor=tenant.get("actor", ""))
+ base = str(request.base_url).rstrip("/")
+ return {
+ "join_url": f"{base}/j/{token}",
+ "expires_at": expiry,
+ "ttl_seconds": TOKEN_TTL_SECONDS,
+ }
+
+ @app.delete("/v1/remote/arm")
+ async def disarm(request: Request) -> Any:
+ if await _tenant(request) is None:
+ return _unauthorized
+ # Disarm clears ALL tokens; on multi-tenant this is coarse but safe
+ # (tokens are 10-minute, single-use — worst case someone re-arms).
+ acceptor.disarm()
+ return {"armed": False}
+
+ # -- device-authorization flow (`openworker auth join`) --------------------
+ # start/poll are machine-facing and tokenless (like /j/ and /ws/machine);
+ # listing and approve/deny ride the GUI's sidecar-token middleware. The
+ # approval MINTS the one join token, bound to the requesting identity —
+ # auth join is a third path to the same enrollment primitive, never a
+ # second primitive.
+
+ @app.post("/v1/remote/device/start")
+ async def device_start(request: Request) -> dict[str, Any]:
+ try:
+ body = await request.json()
+ except Exception:
+ body = {}
+ device_code = pysecrets.token_urlsafe(24)
+ user_code = "-".join(
+ "".join(pysecrets.choice(_USER_CODE_ALPHABET) for _ in range(4))
+ for _ in range(2)
+ )
+ acceptor.ephemera.put_grant(
+ {
+ "device_code": device_code,
+ "user_code": user_code,
+ "name": str(body.get("name") or "machine")[:64],
+ "fingerprint": str(body.get("fingerprint") or "")[:64],
+ "status": "pending",
+ "join_url": "",
+ "created_at": time.time(),
+ "expires_at": time.time() + DEVICE_TTL_SECONDS,
+ }
+ )
+ return {
+ "device_code": device_code,
+ "user_code": user_code,
+ "interval": DEVICE_POLL_SECONDS,
+ "expires_in": DEVICE_TTL_SECONDS,
+ # A deployment that serves the SPA hands out a clickable approval
+ # deep link (the joiner prints it); desktop has no approval web
+ # page, so the hint is the instruction there.
+ "verification_url": (
+ approval_url.format(code=user_code) if approval_url else ""
+ ),
+ "verification_hint": "Approve in the OpenWorker app: Settings → Machines",
+ }
+
+ @app.post("/v1/remote/device/poll")
+ async def device_poll(request: Request) -> dict[str, Any]:
+ try:
+ body = await request.json()
+ except Exception:
+ body = {}
+ grant = acceptor.ephemera.grant_by_device_code(str(body.get("device_code") or ""))
+ if grant is None:
+ return {"status": "expired"}
+ if grant["status"] == "approved":
+ # Single-shot delivery: the join URL leaves the store with this reply.
+ acceptor.ephemera.remove_grant(grant["device_code"])
+ return {"status": "approved", "join_url": grant["join_url"]}
+ if grant["status"] == "denied":
+ acceptor.ephemera.remove_grant(grant["device_code"])
+ return {"status": "denied"}
+ return {"status": "pending", "interval": DEVICE_POLL_SECONDS}
+
+ @app.get("/v1/remote/device")
+ async def device_requests(request: Request) -> Any:
+ if await _tenant(request) is None:
+ return _unauthorized
+ if multi_tenant:
+ # Pending grants belong to no org until approved; listing them
+ # would show every tenant's machine names and fingerprints.
+ # Multi-tenant approval is by typed code only (GitHub-style).
+ return JSONResponse({"error": "approval is by code"}, status_code=404)
+ pending = [
+ {
+ "user_code": g["user_code"],
+ "name": g["name"],
+ "fingerprint": g["fingerprint"],
+ "created_at": g["created_at"],
+ "expires_at": g["expires_at"],
+ }
+ for g in acceptor.ephemera.list_grants()
+ if g["status"] == "pending"
+ ]
+ return {"requests": sorted(pending, key=lambda g: g["created_at"])}
+
+ @app.get("/v1/remote/device/{user_code}")
+ async def device_detail(user_code: str, request: Request) -> Any:
+ """What the approval surface shows before the user confirms: the
+ machine's claimed name + fingerprint. Knowing the code IS the
+ capability (short-lived, high-entropy, single grant)."""
+ if await _tenant(request) is None:
+ return _unauthorized
+ grant = acceptor.ephemera.grant_by_user_code(user_code)
+ if grant is None or grant["status"] != "pending":
+ return JSONResponse({"error": "unknown or expired code"}, status_code=404)
+ return {
+ "user_code": grant["user_code"],
+ "name": grant["name"],
+ "fingerprint": grant["fingerprint"],
+ "expires_at": grant["expires_at"],
+ }
+
+ @app.post("/v1/remote/device/{user_code}/approve")
+ async def device_approve(user_code: str, request: Request) -> Response:
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ grant = acceptor.ephemera.grant_by_user_code(user_code)
+ if grant is None or grant["status"] != "pending":
+ return JSONResponse({"error": "unknown or expired code"}, status_code=404)
+ # Approval CLAIMS the grant into the approver's org: the minted token
+ # carries it, so the machine enrolls as that tenant's.
+ minted = provisioner.mint_token(
+ {
+ "fingerprint": grant["fingerprint"],
+ "org_id": tenant["org_id"],
+ "actor": tenant.get("actor", ""),
+ }
+ )
+ base = str(request.base_url).rstrip("/")
+ acceptor.ephemera.update_grant(
+ grant["device_code"],
+ status="approved",
+ join_url=f"{base}/j/{minted['token']}",
+ )
+ audit.emit(
+ "update",
+ entity_type="device_grant",
+ entity_name=grant["name"],
+ detail={"decision": "approved", "fingerprint": grant["fingerprint"]},
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return JSONResponse({"ok": True})
+
+ @app.post("/v1/remote/device/{user_code}/deny")
+ async def device_deny(user_code: str, request: Request) -> Response:
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ grant = acceptor.ephemera.grant_by_user_code(user_code)
+ if grant is None or grant["status"] != "pending":
+ return JSONResponse({"error": "unknown or expired code"}, status_code=404)
+ acceptor.ephemera.update_grant(grant["device_code"], status="denied")
+ audit.emit(
+ "update",
+ entity_type="device_grant",
+ entity_name=grant["name"],
+ detail={"decision": "denied", "fingerprint": grant["fingerprint"]},
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return JSONResponse({"ok": True})
+
+ @app.get("/v1/machines")
+ async def list_machines(request: Request) -> Any:
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ return {
+ "machines": acceptor.machines(tenant["org_id"]),
+ "armed": acceptor.armed,
+ }
+
+ @app.patch("/v1/machines/{machine_id}")
+ async def rename_machine(machine_id: str, request: Request):
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ if _org_machine(machine_id, tenant) is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ payload = await request.json()
+ name = str(payload.get("name", "")).strip()
+ if not name:
+ return JSONResponse({"error": "name required"}, status_code=400)
+ try:
+ row = registry.rename(machine_id, name)
+ except ValueError as exc:
+ return JSONResponse({"error": str(exc)}, status_code=409)
+ if row is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ live = acceptor.live(machine_id)
+ if live is not None:
+ live.name = row["name"]
+ return {"machine": {"id": row["id"], "name": row["name"]}}
+
+ @app.delete("/v1/machines/{machine_id}")
+ async def remove_machine(machine_id: str, request: Request):
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ row = _org_machine(machine_id, tenant)
+ if row is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ live = acceptor.live(machine_id)
+ if live is not None:
+ return JSONResponse(
+ {"error": "machine is connected; it must leave (or go offline) first"},
+ status_code=409,
+ )
+ if not registry.remove(machine_id):
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ audit.emit(
+ "delete",
+ entity_type="machine",
+ entity_name=row["name"],
+ entity_uid=machine_id,
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return {"removed": machine_id}
+
+ @app.get("/v1/wallet")
+ async def wallet_profiles(request: Request):
+ """Wallet contents by NAME AND TYPE only — never values. Feeds the
+ enrollment card's "provision with my defaults" and the chips UIs."""
+ if await _tenant(request) is None:
+ return _unauthorized
+ if wallet is None:
+ return {"profiles": []}
+ return {"profiles": wallet.status()}
+
+ @app.get("/v1/machines/{machine_id}/secrets")
+ async def machine_secrets(machine_id: str, request: Request):
+ """The deployments ledger + staleness: which wallet profiles this
+ machine holds, and whether the wallet's value changed since (hash
+ comparison — values never flow back)."""
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ if _org_machine(machine_id, tenant) is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ rows = []
+ for row in registry.deploys(machine_id):
+ current = _wallet_hash(wallet, row["profile"])
+ rows.append(
+ {
+ "profile": row["profile"],
+ "deployed_at": row["deployed_at"],
+ # stale: wallet value changed since deploy (rotate = deploy
+ # again — owner ruling: no third verb). missing: profile no
+ # longer in the wallet at all. A wallet-less deployment
+ # (browser-sealed deploys) has no reference to compare —
+ # both fields honestly read false there.
+ "stale": current is not None and current != row["value_hash"],
+ "missing_from_wallet": wallet is not None and current is None,
+ }
+ )
+ return {"secrets": rows}
+
+ @app.post("/v1/machines/{machine_id}/secrets")
+ async def deploy_secrets(machine_id: str, request: Request):
+ """Key deploy, two sources, one frame:
+
+ - Wallet path (`{"profiles": [names]}`): the GUI sends NAMES; the
+ controller resolves values from its own SecretStore, seals them to
+ the machine's pinned sealing key, and pushes.
+ - Sealed path (`{"sealed_b64": …, "profiles": [names]}`, OPE-149):
+ the BROWSER already sealed the payload to that same pinned key;
+ this endpoint is a blind relay — it never sees plaintext, needs no
+ wallet, and records only names in the ledger and audit trail.
+
+ Either way, deploy = copy — the box owns its copy.
+ """
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ known = _org_machine(machine_id, tenant)
+ if known is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ # Org-level policy checkpoint (OPE-150): the embedder may refuse key
+ # pushes per tenant. Enforced HERE at the relay — hiding a button is
+ # cosmetics; this refusal is what a security review tests. The denial
+ # itself is an audit event (who tried, which org said no).
+ if deploy_allowed is not None and not deploy_allowed(tenant):
+ audit.emit(
+ "create",
+ entity_type="secret_deploy",
+ entity_name="(refused)",
+ entity_uid=machine_id,
+ detail={"denied": "key_push_disabled"},
+ success=False,
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return JSONResponse(
+ {
+ "error": "key_push_disabled",
+ "message": "key pushes are turned off for this org.",
+ },
+ status_code=403,
+ )
+ payload = await request.json()
+ sealed_b64 = str(payload.get("sealed_b64") or "")
+ if wallet is None and not sealed_b64:
+ return JSONResponse({"error": "no wallet configured"}, status_code=500)
+ live = acceptor.live(machine_id)
+ if live is None:
+ return JSONResponse({"error": "machine offline"}, status_code=503)
+ seal_pubkey = known.get("seal_pubkey") or ""
+ if not seal_pubkey:
+ return JSONResponse(
+ {
+ "error": "machine has no pinned sealing key yet — "
+ "reconnect it once on current code, then retry"
+ },
+ status_code=409,
+ )
+ names = [str(n) for n in (payload.get("profiles") or []) if str(n).strip()]
+ if not names:
+ return JSONResponse({"error": "profiles required"}, status_code=400)
+ if sealed_b64:
+ sealed = sealed_b64
+ # Ledger hashes come from the client (it alone saw the values);
+ # they only ever drive the staleness display, never a decision.
+ hashes = payload.get("hashes") or {}
+ ledger = {
+ name: str(hashes.get(name) or "browser-sealed") for name in names
+ }
+ else:
+ profiles: dict[str, Any] = {}
+ for name in names:
+ data = wallet.get(name) # resolved: refs to desktop-only env vars
+ if data is None: # would silently break on the box
+ return JSONResponse(
+ {"error": f"profile '{name}' not in the wallet"},
+ status_code=400,
+ )
+ profiles[name] = data
+ sealed = seal_b64(seal_pubkey, json.dumps({"profiles": profiles}).encode())
+ ledger = {name: _hash_profile(data) for name, data in profiles.items()}
+ try:
+ status, body, _ = await live.rpc.request_frame(
+ {"type": "secret_deploy", "sealed_b64": sealed}
+ )
+ except (asyncio.TimeoutError, ConnectionError):
+ return JSONResponse({"error": "machine unreachable"}, status_code=503)
+ if status != 200:
+ detail = _safe_json(body)
+ return JSONResponse(
+ {"error": detail.get("error", "deploy failed")}, status_code=502
+ )
+ for name, value_hash in ledger.items():
+ registry.record_deploy(machine_id, name, value_hash)
+ audit.emit(
+ "create",
+ entity_type="secret_deploy",
+ entity_name=name, # profile NAME — values never reach the log
+ entity_uid=machine_id,
+ detail={
+ "machine": known["name"],
+ **({"source": "browser-sealed"} if sealed_b64 else {}),
+ },
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return {"ok": True, "deployed": sorted(names)}
+
+ @app.post("/v1/machines/{machine_id}/connectors/{name}/connect-sealed")
+ async def connector_connect_sealed(machine_id: str, name: str, request: Request):
+ """Remote manual connect: the client sealed the connector FIELDS to
+ this machine's pinned key; we relay ciphertext and the box runs its
+ own connect (validation included). A credential push, so the same
+ org policy checkpoint as key deploys applies."""
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ known = _org_machine(machine_id, tenant)
+ if known is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ if deploy_allowed is not None and not deploy_allowed(tenant):
+ audit.emit(
+ "create",
+ entity_type="connector_connect",
+ entity_name=name,
+ entity_uid=machine_id,
+ detail={"denied": "key_push_disabled"},
+ success=False,
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return JSONResponse(
+ {
+ "error": "key_push_disabled",
+ "message": "key pushes are turned off for this org.",
+ },
+ status_code=403,
+ )
+ live = acceptor.live(machine_id)
+ if live is None:
+ return JSONResponse({"error": "machine offline"}, status_code=503)
+ payload = await request.json()
+ sealed = str(payload.get("sealed_b64") or "")
+ if not sealed:
+ return JSONResponse({"error": "sealed_b64 required"}, status_code=400)
+ try:
+ status, body, _ = await live.rpc.request_frame(
+ {
+ "type": "connector_connect_sealed",
+ "connector": name,
+ "sealed_b64": sealed,
+ }
+ )
+ except (asyncio.TimeoutError, ConnectionError):
+ return JSONResponse({"error": "machine unreachable"}, status_code=503)
+ detail = _safe_json(body)
+ audit.emit(
+ "create",
+ entity_type="connector_connect",
+ entity_name=name, # connector NAME — fields never reach the log
+ entity_uid=machine_id,
+ detail={"machine": known["name"], "source": "browser-sealed"},
+ success=status == 200 and bool(detail.get("ok")),
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return JSONResponse(detail, status_code=status if status != 200 else 200)
+
+ @app.post("/v1/machines/{machine_id}/connectors/{name}/managed-grant-sealed")
+ async def managed_grant_sealed(machine_id: str, name: str, request: Request):
+ """Browser connect-direct (spec §Cloud-dashboard connect-direct): the
+ dashboard tab sealed a broker OAuth result to this machine's pinned
+ key; we relay ciphertext and the box stores it through its own
+ routine. A credential push — the org's key-push checkpoint applies."""
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ known = _org_machine(machine_id, tenant)
+ if known is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ if deploy_allowed is not None and not deploy_allowed(tenant):
+ audit.emit(
+ "create", entity_type="managed_grant", entity_name=name, entity_uid=machine_id,
+ detail={"denied": "key_push_disabled"}, success=False,
+ actor=tenant["actor"], org_id=tenant["org_id"],
+ )
+ return JSONResponse(
+ {"error": "key_push_disabled", "message": "key pushes are turned off for this org."},
+ status_code=403,
+ )
+ live = await _live_or_wake(machine_id)
+ if live is None:
+ return JSONResponse({"error": "machine offline"}, status_code=503)
+ payload = await request.json()
+ sealed = str(payload.get("sealed_b64") or "")
+ if not sealed:
+ return JSONResponse({"error": "sealed_b64 required"}, status_code=400)
+ try:
+ status, body, _ = await live.rpc.request_frame(
+ {"type": "managed_grant_sealed", "connector": name, "sealed_b64": sealed}
+ )
+ except (asyncio.TimeoutError, ConnectionError):
+ return JSONResponse({"error": "machine unreachable"}, status_code=503)
+ detail = _safe_json(body)
+ audit.emit(
+ "create", entity_type="managed_grant", entity_name=name, entity_uid=machine_id,
+ detail={"machine": known["name"], "source": "browser-sealed"},
+ success=status == 200 and bool(detail.get("ok")),
+ actor=tenant["actor"], org_id=tenant["org_id"],
+ )
+ return JSONResponse(detail, status_code=status if status != 200 else 200)
+
+ @app.delete("/v1/machines/{machine_id}/secrets")
+ async def revoke_secrets(machine_id: str, request: Request):
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ if _org_machine(machine_id, tenant) is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ live = acceptor.live(machine_id)
+ if live is None:
+ # An offline box can't be scrubbed; keeping the ledger row is the
+ # honest state ("this machine still holds that key").
+ return JSONResponse({"error": "machine offline"}, status_code=503)
+ payload = await request.json()
+ names = [str(n) for n in (payload.get("profiles") or []) if str(n).strip()]
+ if not names:
+ return JSONResponse({"error": "profiles required"}, status_code=400)
+ try:
+ status, body, _ = await live.rpc.request_frame(
+ {"type": "secret_revoke", "profiles": names}
+ )
+ except (asyncio.TimeoutError, ConnectionError):
+ return JSONResponse({"error": "machine unreachable"}, status_code=503)
+ if status != 200:
+ detail = _safe_json(body)
+ return JSONResponse(
+ {"error": detail.get("error", "revoke failed")}, status_code=502
+ )
+ for name in names:
+ registry.remove_deploy(machine_id, name)
+ audit.emit(
+ "delete",
+ entity_type="secret_deploy",
+ entity_name=name,
+ entity_uid=machine_id,
+ actor=tenant["actor"],
+ org_id=tenant["org_id"],
+ )
+ return {"ok": True, "revoked": names}
+
+ @app.api_route(
+ "/v1/machines/{machine_id}/p/{path:path}",
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
+ )
+ async def proxy(machine_id: str, path: str, request: Request):
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ known = _org_machine(machine_id, tenant)
+ if known is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ _touch(machine_id)
+ live = await _live_or_wake(machine_id)
+ if live is None:
+ return JSONResponse({"error": "machine offline"}, status_code=503)
+ target = "/" + path
+ if request.url.query:
+ target += "?" + request.url.query
+ body = await request.body()
+ try:
+ status, payload, content_type = await live.rpc.request(
+ request.method,
+ target,
+ body=body or None,
+ content_type=request.headers.get("content-type"),
+ # Session actor (spec §Fleet under the org): the box records WHO
+ # is acting, from the login the controller verified — never from a
+ # header the caller could set.
+ actor=str(tenant.get("actor") or ""),
+ )
+ except asyncio.TimeoutError:
+ return JSONResponse({"error": "machine timed out"}, status_code=504)
+ except ConnectionError:
+ return JSONResponse({"error": "machine disconnected"}, status_code=503)
+ # Tier-2 snapshot: every successful unfiltered session-list fetch doubles
+ # as the offline fallback (greyed, never vanished). Metadata only.
+ if (
+ request.method == "GET"
+ and path == "v1/sessions"
+ and not request.url.query
+ and status == 200
+ ):
+ try:
+ registry.save_sessions_snapshot(machine_id, payload.decode("utf-8"))
+ except Exception:
+ pass
+ # Desktop transcript cache (cache-on-view): a transcript fetched while
+ # connected stays readable read-only while the box is offline.
+ transcript_match = _TRANSCRIPT_PATH.fullmatch(path)
+ if request.method == "GET" and transcript_match and status == 200:
+ try:
+ registry.save_transcript(
+ machine_id, transcript_match.group(1), payload.decode("utf-8")
+ )
+ except Exception:
+ pass
+ return Response(content=payload, status_code=status, media_type=content_type)
+
+ @app.get("/v1/machines/{machine_id}/sessions/{session_id}/messages")
+ async def machine_transcript(machine_id: str, session_id: str, request: Request):
+ """The controller's view of one remote transcript: live (proxied, and
+ re-cached) while the machine is connected; the last synced copy —
+ read-only by construction — while it is offline."""
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ if _org_machine(machine_id, tenant) is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ live = acceptor.live(machine_id)
+ if live is not None:
+ try:
+ status, payload, _ = await live.rpc.request(
+ "GET", f"/v1/sessions/{session_id}/messages"
+ )
+ if status == 200:
+ text = payload.decode("utf-8")
+ registry.save_transcript(machine_id, session_id, text)
+ data = json.loads(text)
+ return {"messages": data.get("messages", []), "live": True}
+ except (asyncio.TimeoutError, ConnectionError, ValueError):
+ pass # fall through to the cache
+ cached = registry.transcript(machine_id, session_id)
+ if cached is None:
+ return {"messages": [], "live": False, "cached": False}
+ try:
+ data = json.loads(cached)
+ except ValueError:
+ return {"messages": [], "live": False, "cached": False}
+ return {"messages": data.get("messages", []), "live": False, "cached": True}
+
+ @app.get("/v1/machines/{machine_id}/sessions")
+ async def machine_sessions(machine_id: str, request: Request):
+ """The controller's view of one machine's sessions: live (proxied) while
+ the machine is connected, the last-known snapshot while it is offline."""
+ tenant = await _tenant(request)
+ if tenant is None:
+ return _unauthorized
+ if _org_machine(machine_id, tenant) is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ live = acceptor.live(machine_id)
+ if live is not None:
+ try:
+ status, payload, _ = await live.rpc.request("GET", "/v1/sessions")
+ if status == 200:
+ registry.save_sessions_snapshot(
+ machine_id, payload.decode("utf-8")
+ )
+ data = json.loads(payload.decode("utf-8"))
+ return {"sessions": data.get("sessions", []), "live": True}
+ except (asyncio.TimeoutError, ConnectionError, ValueError):
+ pass # fall through to the snapshot
+ snapshot = registry.sessions_snapshot(machine_id)
+ if snapshot is None:
+ return {"sessions": [], "live": False}
+ try:
+ data = json.loads(snapshot)
+ except ValueError:
+ return {"sessions": [], "live": False}
+ return {"sessions": data.get("sessions", []), "live": False}
+
+ @app.websocket("/ws/machine")
+ async def ws_machine(ws: WebSocket) -> None:
+ # Never sidecar-token-authenticated: boxes can't (and must not) hold that
+ # token. A browser can't pass the challenge without the private key, but
+ # reject browser origins outright anyway.
+ origin = ws.headers.get("origin")
+ if origin is not None:
+ await ws.close(code=1008)
+ return
+ await ws.accept()
+
+ machine_id = pubkey = ""
+ attached = leased = False
+ heartbeat_task: Optional[asyncio.Task] = None
+ try:
+ hello = json.loads(await ws.receive_text())
+ if hello.get("type") != "hello":
+ await _reject(ws, "bad-handshake")
+ return
+ if int(hello.get("protocol_version", -1)) != ch.PROTOCOL_VERSION:
+ # P1 stance: strict equality. The friendly error IS the feature.
+ await _reject(
+ ws,
+ "protocol-mismatch",
+ f"controller speaks protocol {ch.PROTOCOL_VERSION}, "
+ f"machine spoke {hello.get('protocol_version')} — "
+ "update the older side",
+ )
+ return
+ pubkey = str(hello.get("pubkey", ""))
+ if not pubkey:
+ await _reject(ws, "bad-handshake", "missing pubkey")
+ return
+
+ known = registry.by_pubkey(pubkey)
+ token = str(hello.get("token") or "")
+ grant_org = ""
+ grant_actor = ""
+ grant_provenance: dict[str, str] = {}
+ if known is None:
+ binding = acceptor.consume_token(token)
+ if binding is None:
+ await _reject(
+ ws,
+ "not-enrolled",
+ "unknown machine and no valid enrollment token — arm the "
+ "controller and join with a fresh URL",
+ )
+ return
+ if binding["fingerprint"] and binding["fingerprint"] != _fingerprint(
+ pubkey
+ ):
+ # A device-flow token names the identity the user approved;
+ # any other machine presenting it burns it and gets nothing.
+ await _reject(
+ ws,
+ "wrong-machine",
+ "this join token was approved for a different machine "
+ "identity — request approval again from this machine",
+ )
+ return
+ grant_org = binding["org_id"]
+ grant_actor = str(binding.get("actor") or "")
+ grant_provenance = dict(binding.get("provenance") or {})
+
+ # Both paths prove possession of the private key.
+ nonce = pysecrets.token_bytes(_CHALLENGE_BYTES)
+ await ws.send_text(
+ json.dumps({"type": "challenge", "nonce": ch.encode_body(nonce)})
+ )
+ auth = json.loads(await ws.receive_text())
+ if auth.get("type") != "auth" or not verify_b64(
+ pubkey, nonce, str(auth.get("signature", ""))
+ ):
+ await _reject(ws, "bad-signature")
+ return
+
+ if not acceptor.ephemera.acquire_lease(pubkey):
+ # Clone trap: one concurrent connection per identity. A copied
+ # state dir must not silently become a second "same" machine.
+ await _reject(
+ ws,
+ "already-connected",
+ "a machine with this identity is already connected",
+ )
+ return
+ leased = True
+
+ app_version = str(hello.get("app_version", ""))
+ seal_pubkey = str(hello.get("seal_pubkey", ""))
+ # The challenge only proves the identity key; the sealing key is
+ # pinned only if that same identity key signed it. Without this a
+ # middlebox could swap in its own key and read wallet deploys.
+ if seal_pubkey and not verify_seal_attestation(
+ pubkey, seal_pubkey, str(hello.get("seal_sig", ""))
+ ):
+ await _reject(
+ ws,
+ "bad-seal-attestation",
+ "sealing key is not signed by this machine's identity key",
+ )
+ return
+ if known is None:
+ known = registry.enroll(
+ str(hello.get("name") or "machine"),
+ pubkey,
+ app_version,
+ seal_pubkey,
+ org_id=grant_org,
+ enrolled_by=grant_actor,
+ provenance=str(grant_provenance.get("kind") or ""),
+ provenance_ref=str(grant_provenance.get("ref") or ""),
+ )
+ audit.emit(
+ "create",
+ entity_type="machine",
+ entity_name=known["name"],
+ entity_uid=known["id"],
+ detail={
+ "fingerprint": _fingerprint(pubkey),
+ **({"provenance": grant_provenance["kind"]} if grant_provenance.get("kind") else {}),
+ },
+ org_id=grant_org,
+ )
+ elif seal_pubkey and not known.get("seal_pubkey"):
+ # Backfill: a box enrolled before the sealing key pins it on its
+ # next reconnect. Sound over untrusted transports because the
+ # attestation above ties it to the challenged identity key.
+ registry.set_seal_pubkey(known["id"], seal_pubkey)
+ machine_id = known["id"]
+ registry.touch(machine_id, app_version)
+
+ rpc = ch.RpcClient(ws.send_text)
+ acceptor.attach(machine_id, known["name"], pubkey, rpc)
+ attached = True
+ # Heartbeat for TTL-leased backends: the lease outlives the node
+ # only by its TTL, never forever.
+ refresh = getattr(acceptor.ephemera, "refresh_lease", None)
+ if refresh is not None:
+
+ async def _heartbeat() -> None:
+ while True:
+ await asyncio.sleep(LEASE_REFRESH_SECONDS)
+ refresh(pubkey)
+
+ heartbeat_task = asyncio.create_task(_heartbeat())
+ welcome: dict[str, Any] = {
+ "type": "welcome",
+ "machine_id": machine_id,
+ "name": known["name"],
+ }
+ # Org policy rides the welcome (spec §Audit export): hosted controllers
+ # supply `policy_for(machine_id, known)`; the desktop supplies nothing
+ # and the box keeps whatever record it already holds.
+ if policy_for is not None:
+ try:
+ policy = policy_for(machine_id, known)
+ if asyncio.iscoroutine(policy):
+ policy = await policy
+ except Exception:
+ policy = None
+ if isinstance(policy, dict):
+ welcome["policy"] = policy
+ if policy.get("org_id"):
+ welcome["org_id"] = str(policy["org_id"])
+ await ws.send_text(json.dumps(welcome))
+
+ live = acceptor.live(machine_id)
+ while True:
+ frame = json.loads(await ws.receive_text())
+ kind = frame.get("type")
+ if kind == "rpc_result":
+ rpc.resolve(frame)
+ elif kind == "policy_check":
+ # The box reports the version it holds (spec §Versioned org
+ # policy). Record it — status is what the machine SAYS — then
+ # answer with the newer document or "current".
+ reported = _int(frame.get("version"))
+ _record(policy_status, machine_id, known, reported, "checked")
+ doc = None
+ if policy_for is not None:
+ try:
+ doc = policy_for(machine_id, known)
+ if asyncio.iscoroutine(doc):
+ doc = await doc
+ except Exception:
+ doc = None
+ current = _int((doc or {}).get("version")) if isinstance(doc, dict) else 0
+ if isinstance(doc, dict) and (current > reported or (current == 0 and reported == 0)):
+
+ async def _send_newer(doc=doc, current=current):
+ try:
+ status, body, _ = await rpc.request_frame(
+ {"type": "policy", "policy": doc}
+ )
+ parsed = _safe_json(body)
+ ok = status == 200 and bool(parsed.get("ok"))
+ _record(
+ policy_status,
+ machine_id,
+ known,
+ _int(parsed.get("version")) if ok else reported,
+ "applied" if ok and parsed.get("applied") else ("ignored" if ok else "failed"),
+ )
+ except (asyncio.TimeoutError, ConnectionError):
+ _record(policy_status, machine_id, known, reported, "unreachable")
+
+ asyncio.create_task(_send_newer())
+ else:
+ await ws.send_text(
+ json.dumps({"type": "policy_current", "version": reported})
+ )
+ elif kind == "audit":
+ # Box-originated audit batch (cloud sink). Accepted only where a
+ # sink exists; a controller without one says so and the box backs
+ # off instead of dropping rows.
+ events = frame.get("events")
+ accepted = False
+ if audit_sink is not None and isinstance(events, list):
+ try:
+ res = audit_sink(machine_id, known, events)
+ if asyncio.iscoroutine(res):
+ res = await res
+ accepted = bool(res)
+ except Exception:
+ accepted = False
+ await ws.send_text(
+ json.dumps(
+ {
+ "type": "audit_ack",
+ "id": str(frame.get("id")),
+ "accepted": accepted,
+ "count": len(events) if isinstance(events, list) else 0,
+ }
+ )
+ )
+ elif kind == "ws_msg" and live is not None:
+ gui_ws = live.streams.get(str(frame.get("stream")))
+ if gui_ws is not None:
+ try:
+ await gui_ws.send_text(str(frame.get("text", "")))
+ except Exception:
+ pass # GUI went away; its handler sends ws_close
+ elif kind == "ws_close" and live is not None:
+ gui_ws = live.streams.pop(str(frame.get("stream")), None)
+ if gui_ws is not None:
+ try:
+ await gui_ws.close()
+ except Exception:
+ pass
+ except (WebSocketDisconnect, json.JSONDecodeError, KeyError, ValueError):
+ pass
+ finally:
+ if heartbeat_task is not None:
+ heartbeat_task.cancel()
+ if attached:
+ await acceptor.detach(machine_id, pubkey) # releases the lease
+ elif leased:
+ # Rejected between lease and attach (e.g. bad seal attestation):
+ # free the identity or the real box could never reconnect.
+ acceptor.ephemera.release_lease(pubkey)
+
+ @app.websocket("/ws/machines/{machine_id}/p/{path:path}")
+ async def ws_bridge(ws: WebSocket, machine_id: str, path: str) -> None:
+ """GUI side of a bridged session socket: `/ws/machines/{mid}/p/ws/session/{sid}`
+ behaves exactly like the box's own `/ws/session/{sid}` — the remote home is
+ literally a different base URL. Sidecar-token + Origin gated like /ws/session."""
+ if ws_authenticated is not None and not ws_authenticated(ws):
+ await ws.close(code=1008)
+ return
+ if origin_allowed is not None and not origin_allowed(ws.headers.get("origin")):
+ await ws.close(code=1008)
+ return
+ tenant = await _tenant(ws)
+ if tenant is None:
+ await ws.close(code=1008)
+ return
+ if _org_machine(machine_id, tenant) is None:
+ await ws.close(code=1008) # not this tenant's machine (or unknown)
+ return
+ _touch(machine_id)
+ live = await _live_or_wake(machine_id)
+ if live is None:
+ await ws.close(code=1013) # machine offline: try again later
+ return
+ # Select "openworker" whenever the client OFFERED subprotocols: a
+ # browser treats an unanswered offer as a failed handshake and closes
+ # 1006 the moment the socket opens (python clients are lenient, which
+ # hid this until the first real browser hit the hosted tier — the
+ # api_token gate here only ever covered the desktop deployment).
+ offered = {
+ part.strip()
+ for part in ws.headers.get("sec-websocket-protocol", "").split(",")
+ if part.strip()
+ }
+ await ws.accept(subprotocol="openworker" if "openworker" in offered else None)
+ live.stream_counter += 1
+ stream_id = f"s{live.stream_counter}"
+ live.streams[stream_id] = ws
+ target = "/" + path
+ query = ws.scope.get("query_string", b"").decode()
+ if query:
+ target += "?" + query
+ try:
+ await live.rpc.send_frame(
+ {
+ "type": "ws_open",
+ "stream": stream_id,
+ "path": target,
+ "actor": str(tenant.get("actor") or ""),
+ }
+ )
+ while True:
+ text = await ws.receive_text()
+ await live.rpc.send_frame(
+ {"type": "ws_msg", "stream": stream_id, "text": text}
+ )
+ except (WebSocketDisconnect, ConnectionError):
+ pass
+ finally:
+ if live.streams.pop(stream_id, None) is not None:
+ try:
+ await live.rpc.send_frame({"type": "ws_close", "stream": stream_id})
+ except Exception:
+ pass
+
+ return acceptor
+
+
+async def _reject(ws: WebSocket, reason: str, detail: Optional[str] = None) -> None:
+ try:
+ await ws.send_text(json.dumps(ch.reject_frame(reason, detail)))
+ await ws.close(code=1008)
+ except Exception:
+ pass
+
+
+def _hash_profile(data: Any) -> str:
+ import hashlib
+
+ return hashlib.sha256(
+ json.dumps(data, sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()
+
+
+def _wallet_hash(wallet, profile: str) -> Optional[str]:
+ if wallet is None:
+ return None
+ try:
+ data = wallet.get(profile)
+ except Exception:
+ return None
+ return None if data is None else _hash_profile(data)
+
+
+def _int(value: Any) -> int:
+ try:
+ return max(0, int(value or 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+def _record(policy_status, machine_id: str, known: dict[str, Any], version: int, outcome: str) -> None:
+ """Best-effort status hook: (machine_id, known, version, outcome) where
+ outcome ∈ checked | applied | ignored | failed | unreachable."""
+ if policy_status is None:
+ return
+ try:
+ policy_status(machine_id, known, version, outcome)
+ except Exception:
+ pass
+
+
+def _safe_json(body: bytes) -> dict[str, Any]:
+ try:
+ value = json.loads(body.decode("utf-8"))
+ return value if isinstance(value, dict) else {}
+ except Exception:
+ return {}
diff --git a/coworker/remote/audit.py b/coworker/remote/audit.py
new file mode 100644
index 00000000..aa955e03
--- /dev/null
+++ b/coworker/remote/audit.py
@@ -0,0 +1,90 @@
+"""OCSF-shaped audit trail for acceptor actions — the management plane, v0.
+
+One JSONL file, one event per security-relevant acceptor action: machine
+enrolled/removed/renamed, secrets deployed/revoked, device grants
+approved/denied. Events follow OCSF Entity Management (class_uid 3004,
+category 3: Identity & Access Management) so a SIEM ingests them without a
+custom parser (remote-home-design.md §Planes — management plane starts as
+events, not services). Values never appear here: secrets are named by profile,
+machines by id/name/fingerprint.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any, Optional
+
+_OCSF_VERSION = "1.1.0"
+_CLASS_ENTITY_MANAGEMENT = 3004
+_CATEGORY_IAM = 3
+
+# OCSF Entity Management activity ids.
+_ACTIVITIES = {"create": 1, "read": 2, "update": 3, "delete": 4}
+
+
+class AuditLog:
+ """Append-only JSONL. Write failures never break the action being audited
+ — but they are counted, so tests (and a future health surface) can see."""
+
+ def __init__(self, path: Path) -> None:
+ self.path = Path(path)
+ self.dropped = 0
+
+ def emit(
+ self,
+ activity: str,
+ *,
+ entity_type: str,
+ entity_name: str,
+ entity_uid: str = "",
+ detail: Optional[dict[str, Any]] = None,
+ success: bool = True,
+ actor: str = "",
+ org_id: str = "",
+ ) -> None:
+ """`actor` is the acting identity (account sub or email) and `org_id`
+ the tenant it acted in — both empty on the desktop, REQUIRED in any
+ multi-tenant deployment (SOC2: every control-plane event has a who)."""
+ activity_id = _ACTIVITIES.get(activity, 0)
+ event: dict[str, Any] = {
+ "class_uid": _CLASS_ENTITY_MANAGEMENT,
+ "category_uid": _CATEGORY_IAM,
+ "activity_id": activity_id,
+ "activity_name": activity,
+ "type_uid": _CLASS_ENTITY_MANAGEMENT * 100 + activity_id,
+ "time": int(time.time() * 1000),
+ "severity_id": 1, # informational
+ "status_id": 1 if success else 2,
+ "metadata": {
+ "version": _OCSF_VERSION,
+ "product": {"name": "OpenWorker", "vendor_name": "OpenWorker"},
+ },
+ "entity": {
+ "type": entity_type,
+ "name": entity_name,
+ **({"uid": entity_uid} if entity_uid else {}),
+ },
+ }
+ if actor or org_id:
+ event["actor"] = {"user": {"name": actor}}
+ if org_id:
+ event["actor"]["user"]["org"] = {"uid": org_id}
+ if detail:
+ event["unmapped"] = detail
+ try:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with self.path.open("a", encoding="utf-8") as fh:
+ fh.write(json.dumps(event, separators=(",", ":")) + "\n")
+ except OSError:
+ self.dropped += 1
+
+
+class NullAuditLog:
+ """For embedders that opt out; both real apps pass a file-backed log."""
+
+ dropped = 0
+
+ def emit(self, *args: Any, **kwargs: Any) -> None:
+ pass
diff --git a/coworker/remote/audit_export.py b/coworker/remote/audit_export.py
new file mode 100644
index 00000000..acb89a9e
--- /dev/null
+++ b/coworker/remote/audit_export.py
@@ -0,0 +1,362 @@
+"""Audit export: the box ships its audit EVENTS to a sink, only when policy says so.
+
+Owner ruling 2026-09-02 (remote-home-design.md §Audit export): OFF by default —
+a personal or self-hosted machine sends nothing anywhere. Central governance
+turns it on through the org policy the controller hands the box (welcome frame
++ `policy` pushes); `audit_export` is that policy's field. What leaves the box is
+the audit ROW, not the conversation: tool name, connector, redacted argument
+preview, approval decision, token counts, session/agent ids, resource
+references. Never result bodies, never the model's reasons, never transcripts —
+the cloud stays content-blind.
+
+Two sinks, one emitter:
+- `cloud`: batches ride the existing machine channel as `audit` frames; the
+ controller answers `audit_ack`. No new auth — the socket authenticated at
+ the handshake. Our hosted store powers the Admin SPA from these.
+- `http`: batches POST to a URL (a customer's SIEM/HEC) with optional headers.
+
+At-least-once: the cursor (last exported row id) advances only on ack and is
+persisted beside the state, so a restart resumes where it left off; a sink
+that refuses backs the emitter off rather than dropping rows.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Awaitable, Callable, Optional
+
+_OCSF_VERSION = "1.1.0"
+_CLASS_API_ACTIVITY = 6003 # OCSF Application Activity › API Activity
+_CATEGORY_APPLICATION = 6
+_ACTIVITY_OTHER = 99
+
+POLICY_FILE = "policy.json"
+CURSOR_FILE = "audit-export.json"
+
+# Columns of the local audit row that may NOT leave the box (content).
+_CONTENT_COLUMNS = ("result_preview", "reason")
+
+
+# -- policy ---------------------------------------------------------------------
+
+
+@dataclass
+class ExportPolicy:
+ enabled: bool = False
+ sink: str = "cloud" # "cloud" | "http"
+ url: str = ""
+ headers: dict[str, str] = field(default_factory=dict)
+ batch: int = 200
+ flush_seconds: float = 5.0
+
+ @classmethod
+ def from_policy(cls, policy: Optional[dict[str, Any]]) -> "ExportPolicy":
+ """`policy` is the whole org policy record; this reads its `audit_export`
+ field. Anything malformed reads as OFF — governance never turns on by
+ accident."""
+ raw = (policy or {}).get("audit_export") if isinstance(policy, dict) else None
+ if not isinstance(raw, dict) or not raw.get("enabled"):
+ return cls()
+ sink = str(raw.get("sink") or "cloud").lower()
+ if sink not in ("cloud", "http"):
+ return cls()
+ url = str(raw.get("url") or "")
+ if sink == "http" and not url.startswith(("https://", "http://")):
+ return cls()
+ headers = raw.get("headers") if isinstance(raw.get("headers"), dict) else {}
+ try:
+ batch = max(1, min(int(raw.get("batch") or 200), 1000))
+ flush = max(1.0, min(float(raw.get("flush_seconds") or 5.0), 300.0))
+ except (TypeError, ValueError):
+ batch, flush = 200, 5.0
+ return cls(
+ enabled=True,
+ sink=sink,
+ url=url,
+ headers={str(k): str(v) for k, v in headers.items()},
+ batch=batch,
+ flush_seconds=flush,
+ )
+
+
+def load_policy(state: Path) -> dict[str, Any]:
+ try:
+ data = json.loads((Path(state) / POLICY_FILE).read_text())
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+
+def save_policy(state: Path, policy: dict[str, Any]) -> None:
+ """Persist the org policy the controller handed us, so the machine can SHOW
+ what governs it even while offline (visible-governance rule)."""
+ path = Path(state) / POLICY_FILE
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({**policy, "received_at": time.time()}, indent=2))
+ try:
+ path.chmod(0o600)
+ except OSError:
+ pass
+
+
+# -- OCSF -----------------------------------------------------------------------
+
+
+def to_ocsf(
+ row: dict[str, Any], *, machine_id: str = "", machine_name: str = "", org_id: str = ""
+) -> dict[str, Any]:
+ """One local audit row → one OCSF API Activity event. Content columns are
+ dropped here, structurally, not by a filter someone could forget."""
+ status = str(row.get("status") or "")
+ status_id = 1 if status in ("ok", "ran", "success", "allow") else 2 if status in (
+ "error", "denied", "deny", "failed", "blocked"
+ ) else 99
+ tokens = {
+ k: int(row.get(k) or 0)
+ for k in ("tokens_in", "tokens_out", "cache_read", "cache_write")
+ }
+ try:
+ ts = row.get("timestamp") or ""
+ # SQLite CURRENT_TIMESTAMP is UTC "YYYY-MM-DD HH:MM:SS".
+ from datetime import datetime, timezone
+
+ t_ms = int(
+ datetime.strptime(ts, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc).timestamp()
+ * 1000
+ )
+ except (TypeError, ValueError):
+ t_ms = int(time.time() * 1000)
+ workspace = str(row.get("workspace") or "")
+ event: dict[str, Any] = {
+ "class_uid": _CLASS_API_ACTIVITY,
+ "category_uid": _CATEGORY_APPLICATION,
+ "activity_id": _ACTIVITY_OTHER,
+ "activity_name": str(row.get("stage") or "tool_call"),
+ "type_uid": _CLASS_API_ACTIVITY * 100 + _ACTIVITY_OTHER,
+ "time": t_ms,
+ "severity_id": 1,
+ "status_id": status_id,
+ "status": status,
+ "metadata": {
+ "version": _OCSF_VERSION,
+ "product": {"name": "OpenWorker", "vendor_name": "OpenWorker"},
+ "uid": f"{machine_id}:{row.get('id')}",
+ },
+ "actor": {
+ # The PERSON behind the session (controller-verified login); the coworker
+ # persona rides `unmapped.agent`. Empty user = automated (event-spawned).
+ "user": {
+ "name": str(row.get("actor") or ""),
+ **({"email_addr": str(row["actor"])} if "@" in str(row.get("actor") or "") else {}),
+ **({"org": {"uid": org_id}} if org_id else {}),
+ },
+ "session": {"uid": str(row.get("session_id") or "")},
+ },
+ "api": {
+ "operation": str(row.get("tool") or ""),
+ "service": {"name": str(row.get("connector") or "")},
+ },
+ "device": {"uid": machine_id, "name": machine_name},
+ "unmapped": {
+ "row_id": row.get("id"),
+ "agent": str(row.get("agent") or ""),
+ "automated": not str(row.get("actor") or ""),
+ "approval": str(row.get("approval") or ""),
+ "approved_by": str(row.get("approved_by") or ""),
+ # Already secret-stripped by the local store; still a PREVIEW, not content.
+ "args": row.get("args") if isinstance(row.get("args"), dict) else {},
+ "resource": str(row.get("resource") or ""),
+ "call_id": str(row.get("call_id") or ""),
+ # Basename only: a path is a name, its contents are not ours to ship.
+ "workspace": workspace.rstrip("/").rsplit("/", 1)[-1] if workspace else "",
+ **tokens,
+ },
+ }
+ for col in _CONTENT_COLUMNS:
+ assert col not in event["unmapped"]
+ return event
+
+
+# -- the emitter ---------------------------------------------------------------
+
+
+SendBatch = Callable[[list[dict[str, Any]]], Awaitable[bool]]
+
+
+class AuditExporter:
+ """Watches the local audit store and ships new rows to the policy's sink."""
+
+ def __init__(
+ self,
+ state: Path,
+ store,
+ *,
+ machine_id: str = "",
+ machine_name: str = "",
+ org_id: str = "",
+ policy: Optional[ExportPolicy] = None,
+ backoff_start: float = 5.0,
+ backoff_cap: float = 120.0,
+ ) -> None:
+ self.state = Path(state)
+ self.store = store
+ self.machine_id = machine_id
+ self.machine_name = machine_name
+ self.org_id = org_id
+ self.policy = policy or ExportPolicy()
+ self._backoff_start = backoff_start
+ self._backoff_cap = backoff_cap
+ self._wake = asyncio.Event()
+ self._cursor = self._load_cursor()
+ self.exported = 0
+ self.last_error = ""
+ self.last_sent_at: float = 0.0
+ self._pending_acks: dict[str, asyncio.Future] = {}
+ self._counter = 0
+ # Woken by every local append, so a tool call ships within one flush window.
+ subscribe = getattr(store, "subscribe", None)
+ if subscribe is not None:
+ subscribe(lambda _row: self._wake.set())
+
+ # -- state ------------------------------------------------------------------
+ def _cursor_path(self) -> Path:
+ return self.state / CURSOR_FILE
+
+ def _load_cursor(self) -> int:
+ try:
+ return int(json.loads(self._cursor_path().read_text()).get("last_id") or 0)
+ except (OSError, ValueError, AttributeError):
+ return 0
+
+ def _save_cursor(self) -> None:
+ try:
+ self._cursor_path().parent.mkdir(parents=True, exist_ok=True)
+ self._cursor_path().write_text(
+ json.dumps({"last_id": self._cursor, "sink": self.policy.sink, "at": time.time()})
+ )
+ except OSError:
+ pass
+
+ def set_policy(self, policy: ExportPolicy) -> None:
+ self.policy = policy
+ self._wake.set()
+
+ def pending(self) -> int:
+ rows = self.store.list_since(self._cursor, limit=1)
+ if not rows:
+ return 0
+ # Cheap estimate: the store's newest id minus our cursor.
+ newest = self.store.list(limit=1)
+ return max(0, int(newest[0]["id"]) - self._cursor) if newest else 0
+
+ def status(self) -> dict[str, Any]:
+ """What the machine SHOWS about its governance (visible-governance rule)."""
+ return {
+ "enabled": self.policy.enabled,
+ "sink": self.policy.sink if self.policy.enabled else "",
+ "url": self.policy.url if self.policy.sink == "http" else "",
+ "exported": self.exported,
+ "last_id": self._cursor,
+ "pending": self.pending() if self.policy.enabled else 0,
+ "last_error": self.last_error,
+ "last_sent_at": self.last_sent_at,
+ }
+
+ # -- cloud sink: the channel ------------------------------------------------
+ def ack(self, frame: dict[str, Any]) -> None:
+ """Controller's `audit_ack` for one of our `audit` frames."""
+ fut = self._pending_acks.pop(str(frame.get("id")), None)
+ if fut is not None and not fut.done():
+ fut.set_result(bool(frame.get("accepted")))
+
+ def channel_sender(self, send_frame: Callable[[dict[str, Any]], Awaitable[None]]) -> SendBatch:
+ async def send(events: list[dict[str, Any]]) -> bool:
+ self._counter += 1
+ frame_id = f"a{self._counter}"
+ fut: asyncio.Future = asyncio.get_running_loop().create_future()
+ self._pending_acks[frame_id] = fut
+ try:
+ await send_frame({"type": "audit", "id": frame_id, "events": events})
+ return await asyncio.wait_for(fut, timeout=30.0)
+ except asyncio.TimeoutError:
+ return False
+ finally:
+ self._pending_acks.pop(frame_id, None)
+
+ return send
+
+ # -- http sink -----------------------------------------------------------------
+ def http_sender(self) -> SendBatch:
+ async def send(events: list[dict[str, Any]]) -> bool:
+ import httpx
+
+ try:
+ async with httpx.AsyncClient(timeout=20.0) as client:
+ resp = await client.post(
+ self.policy.url,
+ json={"events": events},
+ headers={"content-type": "application/json", **self.policy.headers},
+ )
+ return 200 <= resp.status_code < 300
+ except httpx.HTTPError:
+ return False
+
+ return send
+
+ # -- the loop -------------------------------------------------------------------
+ async def flush_once(self, send: SendBatch) -> int:
+ """Ship everything past the cursor in batches; returns rows exported.
+ Stops at the first refused batch (the cursor never skips a row)."""
+ total = 0
+ while True:
+ rows = self.store.list_since(self._cursor, limit=self.policy.batch)
+ if not rows:
+ return total
+ events = [
+ to_ocsf(
+ r,
+ machine_id=self.machine_id,
+ machine_name=self.machine_name,
+ org_id=self.org_id,
+ )
+ for r in rows
+ ]
+ ok = await send(events)
+ if not ok:
+ self.last_error = f"sink refused {len(events)} events"
+ raise ConnectionError(self.last_error)
+ self._cursor = int(rows[-1]["id"])
+ self._save_cursor()
+ self.exported += len(rows)
+ self.last_sent_at = time.time()
+ self.last_error = ""
+ total += len(rows)
+
+ async def run(self, send: Optional[SendBatch] = None) -> None:
+ """Serve until cancelled. `send` overrides the sink (tests, or the channel
+ sender for one connection's lifetime). With the policy off this idles."""
+ backoff = self._backoff_start
+ while True:
+ self._wake.clear()
+ if not self.policy.enabled:
+ await self._wake.wait()
+ continue
+ sender = send or (self.http_sender() if self.policy.sink == "http" else None)
+ if sender is None:
+ # cloud sink without a channel (offline): wait for one.
+ await self._wake.wait()
+ continue
+ try:
+ await self.flush_once(sender)
+ backoff = self._backoff_start
+ try:
+ await asyncio.wait_for(self._wake.wait(), timeout=self.policy.flush_seconds)
+ except asyncio.TimeoutError:
+ pass
+ except ConnectionError:
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, self._backoff_cap)
diff --git a/coworker/remote/channel.py b/coworker/remote/channel.py
new file mode 100644
index 00000000..fccfc0f8
--- /dev/null
+++ b/coworker/remote/channel.py
@@ -0,0 +1,290 @@
+"""The reverse channel: a small RPC framing over the box's dialed-out WebSocket.
+
+This is a TRANSPORT ADAPTER, not a protocol of its own. Controller → box
+frames carry an ordinary HTTP request shape (`method`, `path`, `body`); the
+box dispatches them into its OWN ASGI app in-process and answers with the
+response. Every existing /v1 endpoint therefore works remotely with zero
+handler changes. Box → controller `event` frames are reserved for the live
+session stream (P1c).
+
+Frame vocabulary (JSON text frames):
+ handshake box → ctrl {"type": "hello", "protocol_version", "app_version",
+ "pubkey", "name", "token"?}
+ ctrl → box {"type": "challenge", "nonce"}
+ box → ctrl {"type": "auth", "signature"}
+ ctrl → box {"type": "welcome", "machine_id", "name"}
+ | {"type": "reject", "reason", "detail"?}
+ steady ctrl → box {"type": "rpc", "id", "method", "path",
+ "body_b64"?, "content_type"?}
+ box → ctrl {"type": "rpc_result", "id", "status",
+ "body_b64", "content_type"}
+ wallet ctrl → box {"type": "secret_deploy", "id", "sealed_b64"}
+ (sealed) ctrl → box {"type": "secret_revoke", "id", "profiles"}
+ box → ctrl rpc_result for both (status 200/400)
+ websocket ctrl → box {"type": "ws_open", "stream", "path"}
+ (bridged) ctrl → box {"type": "ws_msg", "stream", "text"}
+ ctrl → box {"type": "ws_close", "stream"}
+ box → ctrl {"type": "ws_msg", "stream", "text"}
+ box → ctrl {"type": "ws_close", "stream"}
+
+PROTOCOL_VERSION is checked with STRICT EQUALITY in P1 (owner ruling
+2026-08-24); the field existing in the very first version is the
+un-retrofittable escape hatch that lets later versions negotiate a window.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+from typing import Any, Awaitable, Callable, Optional
+
+# v2: hello carries seal_sig — the sealing key attested by the identity key.
+PROTOCOL_VERSION = 2
+
+# One in-flight RPC must never wedge the channel; the controller-side proxy
+# turns a timeout into a 504 while the socket stays healthy.
+RPC_TIMEOUT_SECONDS = 60.0
+
+
+def app_version() -> str:
+ try:
+ from importlib.metadata import version
+
+ return version("coworker")
+ except Exception:
+ return "0.0.0"
+
+
+def encode_body(body: bytes | None) -> str:
+ return base64.b64encode(body or b"").decode("ascii")
+
+
+def decode_body(body_b64: str | None) -> bytes:
+ return base64.b64decode((body_b64 or "").encode("ascii"))
+
+
+ACTOR_HEADER = "x-openworker-actor"
+
+
+class RpcClient:
+ """Controller side: pending-future bookkeeping over an arbitrary send callable.
+
+ The owning WebSocket handler runs the receive loop and feeds every
+ `rpc_result` frame to `resolve()`; `request()` is what the proxy route
+ awaits. Sends are serialized — concurrent proxy calls share one socket.
+ """
+
+ def __init__(self, send_text: Callable[[str], Awaitable[None]]) -> None:
+ self._send_text = send_text
+ self._send_lock = asyncio.Lock()
+ self._pending: dict[str, asyncio.Future] = {}
+ self._counter = 0
+ self._closed = False
+
+ async def send_frame(self, frame: dict[str, Any]) -> None:
+ """Send an arbitrary channel frame (ws_open/ws_msg/ws_close) on the
+ same socket, serialized with in-flight RPC sends."""
+ if self._closed:
+ raise ConnectionError("machine channel is closed")
+ async with self._send_lock:
+ await self._send_text(json.dumps(frame))
+
+ async def request_frame(
+ self, frame: dict[str, Any], timeout: float = RPC_TIMEOUT_SECONDS
+ ) -> tuple[int, bytes, str]:
+ """Send any id-carrying frame and await its rpc_result (allocates the id)."""
+ if self._closed:
+ raise ConnectionError("machine channel is closed")
+ self._counter += 1
+ rpc_id = f"r{self._counter}"
+ frame = {**frame, "id": rpc_id}
+ fut: asyncio.Future = asyncio.get_running_loop().create_future()
+ self._pending[rpc_id] = fut
+ try:
+ async with self._send_lock:
+ await self._send_text(json.dumps(frame))
+ result = await asyncio.wait_for(fut, timeout=timeout)
+ finally:
+ self._pending.pop(rpc_id, None)
+ return result
+
+ async def request(
+ self,
+ method: str,
+ path: str,
+ body: bytes | None = None,
+ content_type: str | None = None,
+ timeout: float = RPC_TIMEOUT_SECONDS,
+ actor: str = "",
+ ) -> tuple[int, bytes, str]:
+ frame: dict[str, Any] = {
+ "type": "rpc",
+ "method": method.upper(),
+ "path": path,
+ **({"actor": actor} if actor else {}),
+ }
+ if body:
+ frame["body_b64"] = encode_body(body)
+ frame["content_type"] = content_type or "application/json"
+ return await self.request_frame(frame, timeout=timeout)
+
+ def resolve(self, frame: dict[str, Any]) -> None:
+ fut = self._pending.get(str(frame.get("id")))
+ if fut is not None and not fut.done():
+ fut.set_result(
+ (
+ int(frame.get("status", 502)),
+ decode_body(frame.get("body_b64")),
+ str(frame.get("content_type") or "application/json"),
+ )
+ )
+
+ def close(self, reason: str = "machine disconnected") -> None:
+ self._closed = True
+ for fut in self._pending.values():
+ if not fut.done():
+ fut.set_exception(ConnectionError(reason))
+ self._pending.clear()
+
+
+class AsgiDispatcher:
+ """Box side: dispatch an `rpc` frame into the box's own ASGI app in-process."""
+
+ def __init__(self, app: Any) -> None:
+ import httpx
+
+ self._client = httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://joined-box",
+ timeout=RPC_TIMEOUT_SECONDS,
+ )
+
+ async def dispatch(self, frame: dict[str, Any]) -> dict[str, Any]:
+ rpc_id = str(frame.get("id"))
+ try:
+ body = decode_body(frame.get("body_b64"))
+ headers = {}
+ if body:
+ headers["content-type"] = str(
+ frame.get("content_type") or "application/json"
+ )
+ # The controller-verified actor becomes a header only HERE — the box
+ # has no listener, so nothing else can present one.
+ if frame.get("actor"):
+ headers[ACTOR_HEADER] = str(frame["actor"])
+ response = await self._client.request(
+ str(frame.get("method", "GET")),
+ str(frame.get("path", "/")),
+ content=body or None,
+ headers=headers,
+ )
+ return {
+ "type": "rpc_result",
+ "id": rpc_id,
+ "status": response.status_code,
+ "body_b64": encode_body(response.content),
+ "content_type": response.headers.get(
+ "content-type", "application/json"
+ ),
+ }
+ except Exception as exc: # a broken dispatch must answer, not wedge the channel
+ return {
+ "type": "rpc_result",
+ "id": rpc_id,
+ "status": 502,
+ "body_b64": encode_body(
+ json.dumps({"error": f"dispatch failed: {exc}"}).encode()
+ ),
+ "content_type": "application/json",
+ }
+
+ async def aclose(self) -> None:
+ await self._client.aclose()
+
+
+class AsgiWsBridge:
+ """Box side: one bridged WebSocket stream into the box's own ASGI app.
+
+ The controller's GUI-facing socket is spliced to this: `ws_msg` frames feed
+ the app as `websocket.receive` events, and everything the app sends comes
+ back as `ws_msg` frames. The session WebSocket protocol is JSON text both
+ ways, so only text frames are bridged.
+ """
+
+ def __init__(
+ self,
+ app: Any,
+ stream_id: str,
+ path: str,
+ send_frame: Callable[[dict[str, Any]], Awaitable[None]],
+ actor: str = "",
+ ) -> None:
+ self._app = app
+ self.stream_id = stream_id
+ self._path = path
+ self._send_frame = send_frame
+ self._actor = actor
+ self._incoming: asyncio.Queue = asyncio.Queue()
+ self._closed = False
+
+ async def run(self) -> None:
+ path, _, query = self._path.partition("?")
+ scope = {
+ "type": "websocket",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "scheme": "ws",
+ "path": path,
+ "raw_path": path.encode(),
+ "query_string": query.encode(),
+ "root_path": "",
+ "headers": (
+ [(ACTOR_HEADER.encode(), self._actor.encode())] if self._actor else []
+ ),
+ "client": ("channel", 0),
+ "server": ("joined-box", 0),
+ "subprotocols": [],
+ }
+ await self._incoming.put({"type": "websocket.connect"})
+ try:
+ await self._app(scope, self._incoming.get, self._send)
+ except Exception:
+ pass # app-side failure closes the stream below, never the channel
+ finally:
+ await self._close_out()
+
+ def feed_text(self, text: str) -> None:
+ self._incoming.put_nowait({"type": "websocket.receive", "text": text})
+
+ def feed_close(self) -> None:
+ self._closed = True # controller-initiated: no ws_close echo needed
+ self._incoming.put_nowait({"type": "websocket.disconnect", "code": 1000})
+
+ async def _send(self, message: dict[str, Any]) -> None:
+ kind = message["type"]
+ if kind == "websocket.send":
+ text = message.get("text")
+ if text is None and message.get("bytes") is not None:
+ text = bytes(message["bytes"]).decode("utf-8", "replace")
+ if text is not None and not self._closed:
+ await self._send_frame(
+ {"type": "ws_msg", "stream": self.stream_id, "text": text}
+ )
+ elif kind == "websocket.close":
+ await self._close_out()
+
+ async def _close_out(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ try:
+ await self._send_frame({"type": "ws_close", "stream": self.stream_id})
+ except Exception:
+ pass
+
+
+def reject_frame(reason: str, detail: Optional[str] = None) -> dict[str, Any]:
+ frame: dict[str, Any] = {"type": "reject", "reason": reason}
+ if detail:
+ frame["detail"] = detail
+ return frame
diff --git a/coworker/remote/cloudproxy.py b/coworker/remote/cloudproxy.py
new file mode 100644
index 00000000..c8f72fd3
--- /dev/null
+++ b/coworker/remote/cloudproxy.py
@@ -0,0 +1,296 @@
+"""Union view: the desktop sidecar's window onto a hosted cloud registry.
+
+The desktop SPA talks only to its own sidecar; this module gives that sidecar
+a `/v1/cloud/machines*` surface that forwards to the hosted machines service
+with the user's cloud session token. One backend for the SPA, no CORS, and
+the token never enters the webview. The two registries stay separate — this
+is a VIEW, never a merge (spec: "Union view on the signed-in desktop").
+
+Design rule enforced here: a cloud-session problem degrades the cloud
+section, it never errors the local path. Signed out or expired comes back as
+a normal 200 with a `session` state the GUI renders; only true network
+failures surface as 502.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import time
+from typing import Any, Awaitable, Callable, Optional
+
+import httpx
+from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
+from fastapi.responses import JSONResponse, Response
+
+from .identity import seal_b64
+
+# "signed_out" = no cloud profile at all; "expired" = a profile exists but the
+# session could not be refreshed (Auth0 refresh tokens die from inactivity);
+# "ok" = a usable token was produced. The GUI hides the cloud section on
+# signed_out and shows a sign-in-again row on expired.
+TokenProvider = Callable[[], Awaitable[tuple[str, Optional[str]]]]
+
+_ME_TTL_SECONDS = 900.0
+
+
+def mount_cloud_proxy(
+ app: FastAPI,
+ *,
+ token_provider: TokenProvider,
+ base_url: str,
+ wallet=None,
+ ws_authenticated=None,
+ origin_allowed=None,
+ client: Optional[httpx.AsyncClient] = None,
+) -> None:
+ """`token_provider` returns (state, token) — state per the notes above,
+ token only when state == "ok". `wallet` is the desktop SecretStore the
+ wallet-send deploy path resolves names from (values are sealed HERE, to
+ the machine's pinned key — the cloud only ever relays ciphertext).
+ `client` is injectable for tests (httpx.MockTransport)."""
+
+ upstream = client or httpx.AsyncClient(base_url=base_url, timeout=30)
+ me_cache: dict[str, Any] = {"at": 0.0, "org": None}
+
+ async def _forward(
+ method: str,
+ path: str,
+ token: str,
+ *,
+ body: Optional[bytes] = None,
+ content_type: Optional[str] = None,
+ query: str = "",
+ ) -> Response:
+ headers = {"Authorization": f"Bearer {token}"}
+ if content_type:
+ headers["Content-Type"] = content_type
+ try:
+ resp = await upstream.request(
+ method, path + (f"?{query}" if query else ""), content=body, headers=headers
+ )
+ except httpx.HTTPError:
+ return JSONResponse({"error": "cloud unreachable"}, status_code=502)
+ return Response(
+ content=resp.content,
+ status_code=resp.status_code,
+ media_type=resp.headers.get("content-type"),
+ )
+
+ async def _forward_request(path: str, request: Request) -> Response:
+ state, token = await token_provider()
+ if state != "ok":
+ return JSONResponse({"error": "cloud_session", "session": state}, status_code=401)
+ return await _forward(
+ request.method,
+ path,
+ token or "",
+ body=await request.body() or None,
+ content_type=request.headers.get("content-type"),
+ query=request.url.query,
+ )
+
+ async def _org(token: str) -> Optional[dict[str, str]]:
+ if time.monotonic() - me_cache["at"] < _ME_TTL_SECONDS and me_cache["org"]:
+ return me_cache["org"]
+ try:
+ resp = await upstream.get(
+ "/v1/me", headers={"Authorization": f"Bearer {token}"}
+ )
+ if resp.status_code != 200:
+ return me_cache["org"]
+ me = resp.json()
+ row = next(
+ (o for o in me.get("orgs", []) if o.get("id") == me.get("org_id")),
+ None,
+ )
+ me_cache["org"] = {
+ "id": me.get("org_id", ""),
+ "name": (row or {}).get("name") or me.get("org_id", ""),
+ }
+ me_cache["at"] = time.monotonic()
+ except httpx.HTTPError:
+ pass
+ return me_cache["org"]
+
+ @app.get("/v1/cloud/machines")
+ async def cloud_machines() -> Any:
+ state, token = await token_provider()
+ if state != "ok":
+ return {"session": state, "machines": []}
+ try:
+ resp = await upstream.get(
+ "/v1/machines", headers={"Authorization": f"Bearer {token}"}
+ )
+ except httpx.HTTPError:
+ return {"session": "unreachable", "machines": []}
+ if resp.status_code == 401:
+ # The token minted fine but the service refused it — treat like
+ # an expired session rather than a hard error.
+ return {"session": "expired", "machines": []}
+ if resp.status_code != 200:
+ return {"session": "unreachable", "machines": []}
+ rows = resp.json().get("machines", [])
+ return {"session": "ok", "org": await _org(token or ""), "machines": rows}
+
+ @app.api_route("/v1/cloud/machines/{machine_id}", methods=["PATCH", "DELETE"])
+ async def cloud_machine_admin(machine_id: str, request: Request) -> Response:
+ return await _forward_request(f"/v1/machines/{machine_id}", request)
+
+ @app.get("/v1/cloud/machines/{machine_id}/sessions")
+ async def cloud_machine_sessions(machine_id: str, request: Request) -> Response:
+ return await _forward_request(f"/v1/machines/{machine_id}/sessions", request)
+
+ @app.get("/v1/cloud/machines/{machine_id}/sessions/{session_id}/messages")
+ async def cloud_machine_transcript(
+ machine_id: str, session_id: str, request: Request
+ ) -> Response:
+ return await _forward_request(
+ f"/v1/machines/{machine_id}/sessions/{session_id}/messages", request
+ )
+
+ @app.api_route("/v1/cloud/machines/{machine_id}/secrets", methods=["GET", "DELETE"])
+ async def cloud_machine_secrets(machine_id: str, request: Request) -> Response:
+ return await _forward_request(f"/v1/machines/{machine_id}/secrets", request)
+
+ @app.post("/v1/cloud/machines/{machine_id}/secrets")
+ async def cloud_deploy_secrets(machine_id: str, request: Request) -> Response:
+ """Wallet-send to a cloud machine (the OPE-149 increment the union
+ view unlocks): the GUI sends NAMES; values resolve from the desktop
+ wallet and are sealed HERE to the machine's pinned key. The cloud
+ endpoint receives only the sealed blob — the same blind-relay path
+ the browser uses, with wallet-hash provenance in the ledger."""
+ state, token = await token_provider()
+ if state != "ok":
+ return JSONResponse({"error": "cloud_session", "session": state}, status_code=401)
+ payload = await request.json()
+ names = [str(n) for n in (payload.get("profiles") or []) if str(n).strip()]
+ if not names:
+ return JSONResponse({"error": "profiles required"}, status_code=400)
+ if wallet is None:
+ return JSONResponse({"error": "no wallet configured"}, status_code=500)
+ try:
+ resp = await upstream.get(
+ "/v1/machines", headers={"Authorization": f"Bearer {token}"}
+ )
+ rows = resp.json().get("machines", []) if resp.status_code == 200 else []
+ except httpx.HTTPError:
+ return JSONResponse({"error": "cloud unreachable"}, status_code=502)
+ row = next((m for m in rows if m.get("id") == machine_id), None)
+ if row is None:
+ return JSONResponse({"error": "unknown machine"}, status_code=404)
+ seal_pubkey = row.get("seal_pubkey") or ""
+ if not seal_pubkey:
+ return JSONResponse(
+ {"error": "machine has no pinned sealing key yet"}, status_code=409
+ )
+ profiles: dict[str, Any] = {}
+ for name in names:
+ data = wallet.get(name)
+ if data is None:
+ return JSONResponse(
+ {"error": f"profile '{name}' not in the wallet"}, status_code=400
+ )
+ profiles[name] = data
+ from .acceptor import _hash_profile
+
+ sealed = seal_b64(seal_pubkey, json.dumps({"profiles": profiles}).encode())
+ body = {
+ "sealed_b64": sealed,
+ "profiles": names,
+ "hashes": {name: _hash_profile(data) for name, data in profiles.items()},
+ }
+ return await _forward(
+ "POST",
+ f"/v1/machines/{machine_id}/secrets",
+ token or "",
+ body=json.dumps(body).encode(),
+ content_type="application/json",
+ )
+
+ @app.post("/v1/cloud/machines/{machine_id}/connectors/{name}/connect-sealed")
+ async def cloud_connector_connect_sealed(
+ machine_id: str, name: str, request: Request
+ ) -> Response:
+ # Already ciphertext (sealed in the GUI to the machine's pinned key) —
+ # a plain forward; the hosted service relays it blind like key deploys.
+ return await _forward_request(
+ f"/v1/machines/{machine_id}/connectors/{name}/connect-sealed", request
+ )
+
+ @app.api_route(
+ "/v1/cloud/machines/{machine_id}/p/{path:path}",
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
+ )
+ async def cloud_proxy(machine_id: str, path: str, request: Request) -> Response:
+ return await _forward_request(f"/v1/machines/{machine_id}/p/{path}", request)
+
+ @app.websocket("/ws/cloud/machines/{machine_id}/p/{path:path}")
+ async def cloud_ws_bridge(ws: WebSocket, machine_id: str, path: str) -> None:
+ """Bridged session socket for a cloud machine: the sidecar dials the
+ hosted service's own bridge and pipes frames both ways. Gated like
+ every GUI-facing socket (sidecar token + Origin)."""
+ if ws_authenticated is not None and not ws_authenticated(ws):
+ await ws.close(code=1008)
+ return
+ if origin_allowed is not None and not origin_allowed(ws.headers.get("origin")):
+ await ws.close(code=1008)
+ return
+ state, token = await token_provider()
+ if state != "ok":
+ await ws.close(code=1008)
+ return
+ import websockets
+
+ ws_base = base_url.replace("https://", "wss://").replace("http://", "ws://")
+ target = f"{ws_base}/ws/machines/{machine_id}/p/{path}"
+ query = ws.scope.get("query_string", b"").decode()
+ if query:
+ target += "?" + query
+ offered = {
+ part.strip()
+ for part in ws.headers.get("sec-websocket-protocol", "").split(",")
+ if part.strip()
+ }
+ try:
+ upstream_ws = await websockets.connect(
+ target,
+ additional_headers={"Authorization": f"Bearer {token}"},
+ subprotocols=["openworker"],
+ max_size=16 * 1024 * 1024,
+ )
+ except Exception:
+ await ws.close(code=1013) # cloud or machine unreachable: retry later
+ return
+ await ws.accept(subprotocol="openworker" if "openworker" in offered else None)
+
+ async def pump_down() -> None:
+ try:
+ async for frame in upstream_ws:
+ if isinstance(frame, str):
+ await ws.send_text(frame)
+ finally:
+ # Upstream ended: close the GUI side too, or its receive loop
+ # would sit open on a dead bridge.
+ try:
+ await ws.close()
+ except Exception:
+ pass
+
+ down = asyncio.create_task(pump_down())
+ try:
+ while True:
+ text = await ws.receive_text()
+ await upstream_ws.send(text)
+ except (WebSocketDisconnect, Exception):
+ pass
+ finally:
+ down.cancel()
+ try:
+ await upstream_ws.close()
+ except Exception:
+ pass
+ try:
+ await ws.close()
+ except Exception:
+ pass
diff --git a/coworker/remote/identity.py b/coworker/remote/identity.py
new file mode 100644
index 00000000..2cafc28d
--- /dev/null
+++ b/coworker/remote/identity.py
@@ -0,0 +1,201 @@
+"""Machine identity: an ed25519 keypair generated on the box before it ever dials.
+
+The enrollment token's ONLY job is to bind a new public key to the controller
+once; every reconnect proves possession of the private key via challenge-
+response. Lost state dir = lost identity = re-enroll (by design — there is no
+key recovery, and the controller's clone trap refuses a second concurrent
+connection per public key).
+"""
+
+from __future__ import annotations
+
+import base64
+from dataclasses import dataclass
+from pathlib import Path
+
+from cryptography.exceptions import InvalidSignature, InvalidTag
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric.ed25519 import (
+ Ed25519PrivateKey,
+ Ed25519PublicKey,
+)
+from cryptography.hazmat.primitives.asymmetric.x25519 import (
+ X25519PrivateKey,
+ X25519PublicKey,
+)
+from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
+from cryptography.hazmat.primitives.kdf.hkdf import HKDF
+
+KEY_FILENAME = "machine.key"
+# The SEALING key (x25519) is separate from the signing key on purpose: one key,
+# one job. Its public half rides the enrollment hello and is pinned beside the
+# signing key — wallet deploys are encrypted to it, so a future relay forwards
+# ciphertext it cannot read (remote-home-design.md §Keys wallet).
+SEAL_KEY_FILENAME = "machine.seal.key"
+
+_SEAL_INFO = b"openworker-seal-v1"
+# Domain separator for the seal-key attestation: without it, an attacker who can
+# get the box to sign arbitrary bytes could forge an attestation from any
+# signature oracle. The identity key signs ONLY nonces and this tagged message.
+_SEAL_ATTEST_PREFIX = b"openworker-seal-attest-v1"
+
+
+def _b64(data: bytes) -> str:
+ return base64.b64encode(data).decode("ascii")
+
+
+def _unb64(text: str) -> bytes:
+ return base64.b64decode(text.encode("ascii"))
+
+
+@dataclass
+class MachineIdentity:
+ private_key: Ed25519PrivateKey
+ seal_key: X25519PrivateKey
+
+ @property
+ def public_key_b64(self) -> str:
+ raw = self.private_key.public_key().public_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PublicFormat.Raw,
+ )
+ return _b64(raw)
+
+ @property
+ def fingerprint(self) -> str:
+ """Short human-checkable form shown in `status` and the Machines panel."""
+ import hashlib
+
+ raw = _unb64(self.public_key_b64)
+ return hashlib.sha256(raw).hexdigest()[:16]
+
+ def sign_b64(self, data: bytes) -> str:
+ return _b64(self.private_key.sign(data))
+
+ @property
+ def seal_fingerprint(self) -> str:
+ """Fingerprint of the SEALING key — what the dashboard's Keys card
+ shows; `status` prints it so the user can compare the two."""
+ import hashlib
+
+ raw = _unb64(self.seal_public_key_b64)
+ return hashlib.sha256(raw).hexdigest()[:16]
+
+ @property
+ def seal_public_key_b64(self) -> str:
+ raw = self.seal_key.public_key().public_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PublicFormat.Raw,
+ )
+ return _b64(raw)
+
+ def attest_seal_key_b64(self) -> str:
+ """Sign the sealing public key with the identity key. The hello carries
+ this beside seal_pubkey; the acceptor refuses to pin without it —
+ otherwise a middlebox could substitute its own sealing key (the
+ challenge only ever proves the identity key)."""
+ return self.sign_b64(_SEAL_ATTEST_PREFIX + _unb64(self.seal_public_key_b64))
+
+ def unseal_b64(self, blob_b64: str) -> bytes:
+ """Open a payload sealed to this machine's sealing key."""
+ blob = _unb64(blob_b64)
+ if len(blob) < 32 + 16:
+ raise ValueError("sealed blob too short")
+ ephemeral_pub = blob[:32]
+ ciphertext = blob[32:]
+ shared = self.seal_key.exchange(X25519PublicKey.from_public_bytes(ephemeral_pub))
+ key = _seal_kdf(shared, ephemeral_pub, _unb64(self.seal_public_key_b64))
+ try:
+ return ChaCha20Poly1305(key).decrypt(b"\x00" * 12, ciphertext, None)
+ except InvalidTag as exc:
+ raise ValueError("sealed blob failed to authenticate") from exc
+
+
+def _write_private(path: Path, data: bytes) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.touch(mode=0o600, exist_ok=True)
+ path.chmod(0o600)
+ path.write_bytes(data)
+
+
+def load_or_create(state_dir: Path) -> MachineIdentity:
+ """Load the box's keypairs (signing + sealing), creating them (0600) on
+ first use. A pre-sealing state dir grows the sealing key in place."""
+ path = Path(state_dir) / KEY_FILENAME
+ if path.exists():
+ raw = serialization.load_pem_private_key(path.read_bytes(), password=None)
+ if not isinstance(raw, Ed25519PrivateKey):
+ raise ValueError(f"{path} is not an ed25519 private key")
+ key = raw
+ else:
+ key = Ed25519PrivateKey.generate()
+ _write_private(
+ path,
+ key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ),
+ )
+ seal_path = Path(state_dir) / SEAL_KEY_FILENAME
+ if seal_path.exists():
+ raw = serialization.load_pem_private_key(seal_path.read_bytes(), password=None)
+ if not isinstance(raw, X25519PrivateKey):
+ raise ValueError(f"{seal_path} is not an x25519 private key")
+ seal = raw
+ else:
+ seal = X25519PrivateKey.generate()
+ _write_private(
+ seal_path,
+ seal.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ ),
+ )
+ return MachineIdentity(key, seal)
+
+
+def _seal_kdf(shared: bytes, ephemeral_pub: bytes, recipient_pub: bytes) -> bytes:
+ return HKDF(
+ algorithm=hashes.SHA256(),
+ length=32,
+ salt=None,
+ info=_SEAL_INFO + ephemeral_pub + recipient_pub,
+ ).derive(shared)
+
+
+def seal_b64(recipient_pub_b64: str, plaintext: bytes) -> str:
+ """Seal a payload to a machine's pinned sealing key: ephemeral X25519 +
+ ChaCha20-Poly1305. A fresh key per message makes the zero nonce safe."""
+ recipient_raw = _unb64(recipient_pub_b64)
+ recipient = X25519PublicKey.from_public_bytes(recipient_raw)
+ ephemeral = X25519PrivateKey.generate()
+ ephemeral_pub = ephemeral.public_key().public_bytes(
+ encoding=serialization.Encoding.Raw,
+ format=serialization.PublicFormat.Raw,
+ )
+ key = _seal_kdf(ephemeral.exchange(recipient), ephemeral_pub, recipient_raw)
+ ciphertext = ChaCha20Poly1305(key).encrypt(b"\x00" * 12, plaintext, None)
+ return _b64(ephemeral_pub + ciphertext)
+
+
+def verify_seal_attestation(
+ pubkey_b64: str, seal_pubkey_b64: str, signature_b64: str
+) -> bool:
+ """True iff the identity key behind pubkey_b64 signed this sealing key."""
+ try:
+ seal_raw = _unb64(seal_pubkey_b64)
+ except (ValueError, TypeError):
+ return False
+ return verify_b64(pubkey_b64, _SEAL_ATTEST_PREFIX + seal_raw, signature_b64)
+
+
+def verify_b64(pubkey_b64: str, data: bytes, signature_b64: str) -> bool:
+ try:
+ Ed25519PublicKey.from_public_bytes(_unb64(pubkey_b64)).verify(
+ _unb64(signature_b64), data
+ )
+ return True
+ except (InvalidSignature, ValueError, KeyError, TypeError):
+ return False
diff --git a/coworker/remote/joiner.py b/coworker/remote/joiner.py
new file mode 100644
index 00000000..14d245f0
--- /dev/null
+++ b/coworker/remote/joiner.py
@@ -0,0 +1,947 @@
+"""The box side of remote homes: `openworker join / up / status / leave`.
+
+Joined mode runs the ENTIRE existing server — state dir, engines, the full
+ASGI app — with no listener at all. `joiner` dials the controller, proves its
+identity, then serves RPC frames by dispatching them into its own app
+in-process. The box listens on nothing; the controller is the only party it
+ever talks to (one-arrow transport, remote-home-design.md).
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import socket
+import sys
+import time
+from pathlib import Path
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+from . import channel as ch
+from .identity import KEY_FILENAME, SEAL_KEY_FILENAME, MachineIdentity, load_or_create
+
+CONFIG_FILENAME = "remote.json"
+
+_BACKOFF_START = 1.0
+_BACKOFF_CAP = 60.0
+_WS_MAX_SIZE = 16 * 1024 * 1024 # match the server's inbound frame cap
+
+# Handshake rejections that retrying can never fix — surface and exit.
+_FATAL_REJECTS = {
+ "not-enrolled",
+ "bad-signature",
+ "bad-seal-attestation",
+ "protocol-mismatch",
+ "already-connected",
+ "bad-handshake",
+ "wrong-machine",
+}
+
+
+class JoinRejected(Exception):
+ def __init__(self, reason: str, detail: str = "") -> None:
+ super().__init__(detail or reason)
+ self.reason = reason
+ self.detail = detail
+
+
+def _config_path(state: Path) -> Path:
+ return state / CONFIG_FILENAME
+
+
+def load_remote_config(state: Path) -> Optional[dict[str, Any]]:
+ path = _config_path(state)
+ if not path.exists():
+ return None
+ try:
+ cfg = json.loads(path.read_text())
+ return cfg if isinstance(cfg, dict) and cfg.get("controller") else None
+ except Exception:
+ return None
+
+
+def save_remote_config(state: Path, cfg: dict[str, Any]) -> None:
+ from ..secrets import write_private_text
+
+ write_private_text(_config_path(state), json.dumps(cfg, indent=2) + "\n")
+
+
+def parse_join_url(join_url: str) -> tuple[str, str]:
+ """Split http(s)://host:port/j/TOKEN into (controller base, token)."""
+ parts = urlsplit(join_url)
+ if parts.scheme not in ("http", "https") or not parts.netloc:
+ raise ValueError(f"not a join URL: {join_url}")
+ segments = [s for s in parts.path.split("/") if s]
+ if len(segments) != 2 or segments[0] != "j" or not segments[1]:
+ raise ValueError(f"not a join URL (expected …/j/<token>): {join_url}")
+ return f"{parts.scheme}://{parts.netloc}", segments[1]
+
+
+def _ws_url(controller: str) -> str:
+ parts = urlsplit(controller)
+ scheme = "wss" if parts.scheme == "https" else "ws"
+ return f"{scheme}://{parts.netloc}/ws/machine"
+
+
+def default_name() -> str:
+ return socket.gethostname().split(".")[0] or "machine"
+
+
+async def _handshake(
+ ws, identity: MachineIdentity, name: str, token: Optional[str]
+) -> dict[str, Any]:
+ hello: dict[str, Any] = {
+ "type": "hello",
+ "protocol_version": ch.PROTOCOL_VERSION,
+ "app_version": ch.app_version(),
+ "pubkey": identity.public_key_b64,
+ # Sealing key (wallet): pinned at enrollment; deploys are encrypted to it.
+ # Attested by the identity key — the acceptor won't pin it otherwise.
+ "seal_pubkey": identity.seal_public_key_b64,
+ "seal_sig": identity.attest_seal_key_b64(),
+ "name": name,
+ }
+ if token:
+ hello["token"] = token
+ await ws.send(json.dumps(hello))
+ frame = json.loads(await ws.recv())
+ if frame.get("type") == "reject":
+ raise JoinRejected(str(frame.get("reason", "")), str(frame.get("detail", "")))
+ if frame.get("type") != "challenge":
+ raise JoinRejected("bad-handshake", f"unexpected frame: {frame.get('type')}")
+ signature = identity.sign_b64(ch.decode_body(frame.get("nonce")))
+ await ws.send(json.dumps({"type": "auth", "signature": signature}))
+ frame = json.loads(await ws.recv())
+ if frame.get("type") == "reject":
+ raise JoinRejected(str(frame.get("reason", "")), str(frame.get("detail", "")))
+ if frame.get("type") != "welcome":
+ raise JoinRejected("bad-handshake", f"unexpected frame: {frame.get('type')}")
+ return frame
+
+
+async def _serve_channel(
+ ws,
+ dispatcher: ch.AsgiDispatcher,
+ app,
+ identity: Optional[MachineIdentity] = None,
+ exporter=None,
+ state: Optional[Path] = None,
+) -> None:
+ """Steady state: dispatch each RPC concurrently so a slow request never
+ blocks the next one; bridged WebSocket streams (live sessions) run as their
+ own tasks; all replies share one send lock."""
+ send_lock = asyncio.Lock()
+ tasks: set[asyncio.Task] = set()
+ streams: dict[str, ch.AsgiWsBridge] = {}
+
+ async def send_frame(frame: dict[str, Any]) -> None:
+ async with send_lock:
+ await ws.send(json.dumps(frame))
+
+ async def handle(frame: dict[str, Any]) -> None:
+ await send_frame(await dispatcher.dispatch(frame))
+
+ async def reply(frame_id: str, status: int, body: dict[str, Any]) -> None:
+ await send_frame(
+ {
+ "type": "rpc_result",
+ "id": frame_id,
+ "status": status,
+ "body_b64": ch.encode_body(json.dumps(body).encode()),
+ "content_type": "application/json",
+ }
+ )
+
+ async def handle_secret_deploy(frame: dict[str, Any]) -> None:
+ """Wallet deploy: unseal with OUR private key, write to OUR SecretStore.
+ Deploy = copy — from here on this home owns its copy."""
+ frame_id = str(frame.get("id"))
+ if identity is None:
+ await reply(frame_id, 400, {"error": "no identity; cannot unseal"})
+ return
+ try:
+ payload = json.loads(identity.unseal_b64(str(frame.get("sealed_b64", ""))))
+ profiles = payload.get("profiles")
+ if not isinstance(profiles, dict) or not profiles:
+ raise ValueError("no profiles in payload")
+ secrets = app.state.manager.secrets
+ for profile, data in profiles.items():
+ if not isinstance(data, dict):
+ raise ValueError(f"profile '{profile}' is not an object")
+ secrets.put(str(profile), data)
+ # A deployed provider key behaves like one pasted in Settings:
+ # client rebuilt, recommended model surfaced, and it becomes the
+ # default when the current one cannot run (fresh sandboxes).
+ adopt = getattr(app.state.manager, "adopt_provider_default", None)
+ if adopt is not None:
+ for profile in profiles:
+ if str(profile).startswith("provider:"):
+ try:
+ adopt(str(profile)[len("provider:"):])
+ except Exception:
+ pass
+ # Hot-add listeners: a deployed Slack/GitHub grant (machine
+ # handoff, spec §Managed events) should start polling without a
+ # restart — the same gateway refresh a local connect triggers.
+ if any(
+ str(p).startswith(("slack:", "github:")) for p in profiles
+ ):
+ spawn(app.state.manager.refresh_gateway())
+ await reply(frame_id, 200, {"ok": True, "profiles": sorted(profiles)})
+ except (ValueError, json.JSONDecodeError) as exc:
+ await reply(frame_id, 400, {"error": str(exc)})
+
+ async def handle_managed_grant_sealed(frame: dict[str, Any]) -> None:
+ """Browser connect-direct (spec §Cloud-dashboard connect-direct): the
+ dashboard tab sealed the broker's callback result — grant fields plus
+ the delegation (broker user id, machine credential) — to OUR key. We
+ unseal and run the same bundle routine the desktop uses to stage a
+ grant for a machine, into our own store, then refresh listeners."""
+ frame_id = str(frame.get("id"))
+ if identity is None:
+ await reply(frame_id, 400, {"error": "no identity; cannot unseal"})
+ return
+ name = str(frame.get("connector") or "")
+ try:
+ payload = json.loads(identity.unseal_b64(str(frame.get("sealed_b64", ""))))
+ form = payload.get("form")
+ if not name or not isinstance(form, dict):
+ raise ValueError("connector name and form required")
+ except (ValueError, json.JSONDecodeError) as exc:
+ await reply(frame_id, 400, {"error": str(exc)})
+ return
+ from ..connectors.setup import store_managed_grant_bundle
+
+ grant = {
+ "user_id": str(payload.get("broker_user_id") or ""),
+ "machine_credential": str(payload.get("machine_credential") or ""),
+ }
+ manager = app.state.manager
+ try:
+ result = store_managed_grant_bundle(manager.secrets, name, form, grant)
+ except Exception as exc: # noqa: BLE001 — the tab shows the reason
+ await reply(frame_id, 400, {"error": str(exc)[:200]})
+ return
+ if result.get("ok"):
+ spawn(manager.refresh_gateway())
+ await reply(frame_id, 200, {"ok": True, "account": result.get("account", "")})
+ else:
+ await reply(frame_id, 400, {"error": str(result.get("error") or "could not store the grant")})
+
+ async def handle_secret_revoke(frame: dict[str, Any]) -> None:
+ frame_id = str(frame.get("id"))
+ removed = []
+ secrets = app.state.manager.secrets
+ for profile in frame.get("profiles") or []:
+ if secrets.delete(str(profile)):
+ removed.append(str(profile))
+ await reply(frame_id, 200, {"ok": True, "removed": removed})
+
+ async def handle_connector_connect_sealed(frame: dict[str, Any]) -> None:
+ """Remote manual connect (union view): the controller relays
+ CIPHERTEXT; the fields unseal here and run this box's own connect
+ endpoint — full validation and listener refresh, exactly as if typed
+ locally. Credentials never transit readable."""
+ frame_id = str(frame.get("id"))
+ if identity is None:
+ await reply(frame_id, 400, {"error": "no identity; cannot unseal"})
+ return
+ name = str(frame.get("connector") or "")
+ try:
+ payload = json.loads(identity.unseal_b64(str(frame.get("sealed_b64", ""))))
+ fields = payload.get("fields")
+ if not name or not isinstance(fields, dict):
+ raise ValueError("connector name and fields required")
+ except (ValueError, json.JSONDecodeError) as exc:
+ await reply(frame_id, 400, {"error": str(exc)})
+ return
+ body = json.dumps(
+ {"fields": fields, "acknowledge_risk": bool(payload.get("acknowledge_risk"))}
+ ).encode()
+ await send_frame(
+ await dispatcher.dispatch(
+ {
+ "id": frame_id,
+ "method": "POST",
+ "path": f"/v1/connectors/{name}/connect",
+ "body_b64": ch.encode_body(body),
+ "content_type": "application/json",
+ }
+ )
+ )
+
+ async def handle_policy(frame: dict[str, Any]) -> None:
+ """A newer org policy document (answer to our check, or a controller-
+ initiated send): persist, apply, CONFIRM the version now held. The
+ machine keeps the record so it can SHOW what governs it offline."""
+ frame_id = str(frame.get("id"))
+ policy = frame.get("policy")
+ if not isinstance(policy, dict):
+ await reply(frame_id, 400, {"error": "policy must be an object"})
+ return
+ try:
+ applied, version = apply_policy(app, policy, state=state, exporter=exporter)
+ except Exception as exc: # a bad document must never take the channel down
+ await reply(frame_id, 500, {"ok": False, "error": str(exc), "version": policy_version(held_policy(app))})
+ return
+ await reply(
+ frame_id,
+ 200,
+ {"ok": True, "applied": applied, "version": version, "keys": sorted(policy)},
+ )
+
+ async def policy_checks() -> None:
+ """Tell the controller which version we hold — once right after the
+ welcome (so a fresh connection shows truthful status at once), then
+ every POLICY_CHECK_SECONDS (jittered). It answers `policy_current` or
+ a newer `policy`."""
+ import random
+
+ while True:
+ await send_frame(
+ {
+ "type": "policy_check",
+ "version": policy_version(held_policy(app)),
+ "app_version": ch.app_version(),
+ }
+ )
+ await asyncio.sleep(POLICY_CHECK_SECONDS * random.uniform(0.9, 1.1))
+
+ def spawn(coro) -> None:
+ task = asyncio.create_task(coro)
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+
+ check_task = asyncio.create_task(policy_checks())
+ tasks.add(check_task)
+ check_task.add_done_callback(tasks.discard)
+
+ export_task: Optional[asyncio.Task] = None
+ if exporter is not None:
+ # The cloud sink for THIS connection's lifetime: audit frames ride the
+ # same socket, acks come back through the loop below.
+ export_task = asyncio.create_task(exporter.run(exporter.channel_sender(send_frame)))
+ tasks.add(export_task)
+ export_task.add_done_callback(tasks.discard)
+
+ try:
+ async for raw in ws:
+ try:
+ frame = json.loads(raw)
+ except json.JSONDecodeError:
+ continue
+ kind = frame.get("type")
+ if kind == "rpc":
+ spawn(handle(frame))
+ elif kind == "secret_deploy":
+ spawn(handle_secret_deploy(frame))
+ elif kind == "secret_revoke":
+ spawn(handle_secret_revoke(frame))
+ elif kind == "connector_connect_sealed":
+ spawn(handle_connector_connect_sealed(frame))
+ elif kind == "managed_grant_sealed":
+ spawn(handle_managed_grant_sealed(frame))
+ elif kind == "policy":
+ spawn(handle_policy(frame))
+ elif kind == "policy_current":
+ pass # our check found nothing newer
+ elif kind == "audit_ack":
+ if exporter is not None:
+ exporter.ack(frame)
+ elif kind == "ws_open":
+ stream_id = str(frame.get("stream"))
+ bridge = ch.AsgiWsBridge(
+ app,
+ stream_id,
+ str(frame.get("path", "/")),
+ send_frame,
+ actor=str(frame.get("actor") or ""),
+ )
+ streams[stream_id] = bridge
+
+ async def run_bridge(b=bridge, sid=stream_id):
+ try:
+ await b.run()
+ finally:
+ streams.pop(sid, None)
+
+ spawn(run_bridge())
+ elif kind == "ws_msg":
+ bridge = streams.get(str(frame.get("stream")))
+ if bridge is not None:
+ bridge.feed_text(str(frame.get("text", "")))
+ elif kind == "ws_close":
+ bridge = streams.pop(str(frame.get("stream")), None)
+ if bridge is not None:
+ bridge.feed_close()
+ finally:
+ for task in tasks:
+ task.cancel()
+
+
+POLICY_CHECK_SECONDS = 300.0 # the box asks for a newer document this often (spec: 5 min)
+
+
+def policy_version(doc: Optional[dict[str, Any]]) -> int:
+ """The document's version; 0 when unversioned (desktop controllers, tests)."""
+ try:
+ return max(0, int((doc or {}).get("version") or 0))
+ except (TypeError, ValueError):
+ return 0
+
+
+def held_policy(app) -> dict[str, Any]:
+ manager = getattr(app.state, "manager", None)
+ return dict(getattr(manager, "org_policy", None) or {})
+
+
+def apply_policy(
+ app, policy: dict[str, Any], *, state: Optional[Path] = None, exporter=None
+) -> tuple[bool, int]:
+ """Persist + apply an org policy DOCUMENT on this box (spec §Versioned org
+ policy). Today one field acts: `audit_export` (remote/audit_export.py).
+ Unknown keys are kept verbatim so the machine can display them; nothing
+ turns on by accident. A document OLDER than the one held is ignored — a
+ stale controller never rolls a machine back. Returns (applied, version
+ now held)."""
+ from .audit_export import ExportPolicy, save_policy
+
+ incoming, current = policy_version(policy), policy_version(held_policy(app))
+ if incoming and current and incoming < current:
+ return False, current
+ if state is not None:
+ save_policy(state, policy)
+ manager = getattr(app.state, "manager", None)
+ if manager is not None:
+ manager.org_policy = dict(policy)
+ if exporter is not None:
+ exporter.set_policy(ExportPolicy.from_policy(policy))
+ return True, incoming
+
+
+def _build_exporter(state: Path, app, welcome: dict[str, Any]):
+ from .audit_export import AuditExporter, ExportPolicy, load_policy
+
+ manager = getattr(app.state, "manager", None)
+ store = getattr(manager, "audit_store", None)
+ if store is None:
+ return None
+ exporter = AuditExporter(
+ state,
+ store,
+ machine_id=str(welcome.get("machine_id") or ""),
+ machine_name=str(welcome.get("name") or ""),
+ org_id=str(welcome.get("org_id") or ""),
+ policy=ExportPolicy.from_policy(load_policy(state)),
+ )
+ manager.audit_exporter = exporter
+ # The stored document is what governs us until a newer one arrives —
+ # restore it so version compare and the settings display see it.
+ stored = load_policy(state)
+ if stored and not getattr(manager, "org_policy", None):
+ manager.org_policy = stored
+ return exporter
+
+
+async def run_joined(
+ *,
+ state: Path,
+ controller: str,
+ name: str,
+ token: Optional[str] = None,
+ app=None,
+ once: bool = False,
+ on_welcome=None,
+ log=print,
+) -> None:
+ """Dial the controller and serve until stopped.
+
+ `app`/`once`/`on_welcome` exist for tests and for `join` (which must save
+ config after the first welcome). With `once=False` this reconnects forever
+ with capped exponential backoff — the systemd story is just `up`.
+ """
+ import websockets
+
+ identity = load_or_create(state)
+ if app is None:
+ app = _build_local_app(state)
+ # Machine-held event queues (machines spec §Managed events) are sealed to
+ # this box's pinned key — hand the gateway the unseal so poll transports
+ # can open them. Only joined boxes ever have this attribute.
+ manager = getattr(app.state, "manager", None)
+ if manager is not None:
+ manager.machine_unseal = identity.unseal_b64
+
+ exporter = None
+ async with _lifespan(app):
+ dispatcher = ch.AsgiDispatcher(app)
+ try:
+ backoff = _BACKOFF_START
+ while True:
+ try:
+ async with websockets.connect(
+ _ws_url(controller), max_size=_WS_MAX_SIZE
+ ) as ws:
+ welcome = await _handshake(ws, identity, name, token)
+ token = None # single-use by design; reconnects sign the challenge
+ backoff = _BACKOFF_START
+ log(
+ f"[openworker] joined {controller} as "
+ f"'{welcome.get('name')}' (machine {welcome.get('machine_id')})"
+ )
+ if on_welcome is not None:
+ on_welcome(welcome)
+ on_welcome = None
+ if exporter is None:
+ exporter = _build_exporter(state, app, welcome)
+ # The welcome may carry the org policy (hosted controllers);
+ # a desktop controller sends none and the stored record stands.
+ if isinstance(welcome.get("policy"), dict):
+ apply_policy(app, welcome["policy"], state=state, exporter=exporter)
+ await _serve_channel(
+ ws, dispatcher, app, identity, exporter=exporter, state=state
+ )
+ log("[openworker] controller closed the connection")
+ except JoinRejected as exc:
+ if exc.reason in _FATAL_REJECTS:
+ raise
+ log(f"[openworker] rejected ({exc.reason}); retrying")
+ except (OSError, websockets.WebSocketException) as exc:
+ log(f"[openworker] connection failed: {exc}")
+ if once:
+ return
+ log(f"[openworker] reconnecting in {backoff:.0f}s")
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, _BACKOFF_CAP)
+ finally:
+ await dispatcher.aclose()
+
+
+def _build_local_app(state: Path):
+ """The full server app over this state dir — engines, sessions, everything.
+
+ No listener exists, so no sidecar token: the only way in is the channel,
+ which authenticated at the handshake.
+ """
+ import os
+
+ from ..config import load_config
+ from ..permissions import Mode
+ from ..server.app import create_app
+ from ..server.manager import SessionManager
+
+ os.environ.pop("COWORKER_API_TOKEN", None)
+ cfg = load_config()
+ manager = SessionManager(data_dir=state, model=cfg.model, mode=Mode(cfg.mode))
+ return create_app(manager)
+
+
+def _lifespan(app):
+ """Run the app's lifespan (gateway start / MCP close) — uvicorn isn't here to do it."""
+ return app.router.lifespan_context(app)
+
+
+# -- CLI ----------------------------------------------------------------------
+
+
+def cli(argv: Optional[list[str]] = None) -> int:
+ from ..secrets import state_dir
+
+ parser = argparse.ArgumentParser(
+ prog="openworker",
+ description="Remote-home commands: run this OpenWorker headless, joined to a controller.",
+ )
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ p_join = sub.add_parser("join", help="enroll with a controller and start serving")
+ p_join.add_argument("url", help="join URL from the controller (…/j/<token>)")
+ p_join.add_argument("--name", default=None, help="machine name (default: hostname)")
+
+ # `auth join`: no token in hand — ask the controller for approval (device
+ # flow), then run the SAME enrollment with the token the approval minted.
+ p_auth = sub.add_parser("auth", help="account-approved enrollment (no join URL needed)")
+ auth_sub = p_auth.add_subparsers(dest="auth_command", required=True)
+ p_auth_join = auth_sub.add_parser(
+ "join", help="request approval from the controller, then enroll and serve"
+ )
+ p_auth_join.add_argument("url", help="controller base URL (e.g. http://127.0.0.1:8765)")
+ p_auth_join.add_argument("--name", default=None, help="machine name (default: hostname)")
+
+ sub.add_parser("up", help="start serving with the stored identity")
+ sub.add_parser("status", help="show this machine's remote-home state")
+ # Box-side provisioning (remote-home-design.md §Keys wallet, door 2): write
+ # secrets straight into THIS machine's store — the wallet never in the path.
+ p_secrets = sub.add_parser("secrets", help="manage this machine's local secrets")
+ secrets_sub = p_secrets.add_subparsers(dest="secrets_command", required=True)
+ p_set = secrets_sub.add_parser("set", help="write one profile: NAME key=value …")
+ p_set.add_argument("profile")
+ p_set.add_argument("pairs", nargs="+", help="key=value fields (e.g. api_key=sk-…)")
+ secrets_sub.add_parser("list", help="list profiles (names only, never values)")
+ p_leave = sub.add_parser("leave", help="forget enrollment AND identity on this box")
+ p_leave.add_argument("--yes", action="store_true", help="skip confirmation")
+ # The systemd story: `up` under a unit, restarted forever (P1d).
+ p_service = sub.add_parser("service", help="run this joined machine under systemd")
+ service_sub = p_service.add_subparsers(dest="service_command", required=True)
+ p_install = service_sub.add_parser(
+ "install", help="write + enable a user unit running `openworker up`"
+ )
+ p_install.add_argument(
+ "--force", action="store_true", help="replace another unit already pinned to this state dir"
+ )
+ p_uninstall = service_sub.add_parser("uninstall", help="disable and remove the unit")
+ p_uninstall.add_argument("--unit", default=None, help="unit file name (default: this machine's)")
+ service_sub.add_parser("list", help="show every openworker unit on this box and its state dir")
+
+ args = parser.parse_args(argv)
+ state = state_dir()
+ state.mkdir(parents=True, exist_ok=True)
+
+ if args.command == "join":
+ return _cmd_join(state, args.url, args.name)
+ if args.command == "auth":
+ return _cmd_auth_join(state, args.url, args.name)
+ if args.command == "up":
+ return _cmd_up(state)
+ if args.command == "status":
+ return _cmd_status(state)
+ if args.command == "leave":
+ return _cmd_leave(state, args.yes)
+ if args.command == "secrets":
+ return _cmd_secrets(state, args)
+ if args.command == "service":
+ return _cmd_service(state, args)
+ return 2
+
+
+def _cmd_join(state: Path, url: str, name: Optional[str]) -> int:
+ try:
+ controller, token = parse_join_url(url)
+ except ValueError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ chosen = name or default_name()
+
+ def on_welcome(welcome: dict[str, Any]) -> None:
+ save_remote_config(
+ state,
+ {
+ "controller": controller,
+ "name": welcome.get("name", chosen),
+ "machine_id": welcome.get("machine_id", ""),
+ },
+ )
+
+ return _run(state, controller, chosen, token=token, on_welcome=on_welcome)
+
+
+def _cmd_auth_join(
+ state: Path, url: str, name: Optional[str], poll_interval: Optional[float] = None
+) -> int:
+ """Device flow: print a code, wait for approval in the controller UI, then
+ run the ordinary token join. `poll_interval` overrides the server's pacing
+ (tests only)."""
+ import httpx
+
+ base = url.rstrip("/")
+ if not base.startswith(("http://", "https://")):
+ print("error: controller URL must be http(s)", file=sys.stderr)
+ return 2
+ chosen = name or default_name()
+ identity = load_or_create(state)
+ try:
+ resp = httpx.post(
+ f"{base}/v1/remote/device/start",
+ json={"name": chosen, "fingerprint": identity.fingerprint},
+ timeout=10,
+ )
+ resp.raise_for_status()
+ except httpx.HTTPError as exc:
+ print(f"error: could not reach controller: {exc}", file=sys.stderr)
+ return 1
+ start = resp.json()
+ hint = start.get("verification_url") or start.get("verification_hint") or ""
+ print(f"[openworker] this machine: {chosen} (fingerprint {identity.fingerprint})")
+ print(f"[openworker] approval code: {start['user_code']}")
+ if hint:
+ print(f"[openworker] {hint}")
+ print("[openworker] waiting for approval…")
+
+ interval = poll_interval if poll_interval is not None else float(start.get("interval") or 5)
+ deadline = time.monotonic() + float(start.get("expires_in") or 900)
+ while time.monotonic() < deadline:
+ time.sleep(interval)
+ try:
+ poll = httpx.post(
+ f"{base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ timeout=10,
+ ).json()
+ except httpx.HTTPError:
+ continue # transient (tunnel blip): the grant waits on the controller
+ status = poll.get("status")
+ if status == "pending":
+ continue
+ if status == "approved":
+ # Join against the URL the user gave us — the base the controller
+ # printed into join_url may not be reachable from here (tunnels).
+ _, token = parse_join_url(str(poll.get("join_url", "")))
+ print("[openworker] approved — enrolling")
+ return _cmd_join(state, f"{base}/j/{token}", chosen)
+ print(f"error: approval {status or 'failed'}", file=sys.stderr)
+ return 1
+ print("error: approval timed out", file=sys.stderr)
+ return 1
+
+
+def _cmd_up(state: Path) -> int:
+ cfg = load_remote_config(state)
+ if cfg is None:
+ print(
+ "error: this machine has not joined a controller (run `openworker join <url>`)",
+ file=sys.stderr,
+ )
+ return 2
+ return _run(state, cfg["controller"], str(cfg.get("name") or default_name()))
+
+
+def _run(state: Path, controller: str, name: str, token=None, on_welcome=None) -> int:
+ from ..statelock import EngineBusy, acquire
+
+ # One engine per state dir (statelock.py). A supervisor restart may find
+ # the previous process still tearing down, so wait a little before refusing.
+ try:
+ _lock = acquire(state, timeout=10.0) # noqa: F841 — held for the process's life
+ except EngineBusy as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 3
+ try:
+ asyncio.run(
+ run_joined(
+ state=state,
+ controller=controller,
+ name=name,
+ token=token,
+ on_welcome=on_welcome,
+ )
+ )
+ return 0
+ except KeyboardInterrupt:
+ print("\n[openworker] stopped")
+ return 0
+ except JoinRejected as exc:
+ print(f"error: {exc.reason}: {exc.detail or 'rejected by controller'}", file=sys.stderr)
+ return 1
+
+
+def _cmd_secrets(state: Path, args) -> int:
+ from ..secrets import SecretStore
+
+ store = SecretStore(state / "secrets.json")
+ if args.secrets_command == "list":
+ rows = store.status()
+ if not rows:
+ print("no secrets stored")
+ for row in rows:
+ print(row["profile"] + (f" ({row['type']})" if row.get("type") else ""))
+ return 0
+ data: dict[str, str] = {}
+ for pair in args.pairs:
+ key, sep, value = pair.partition("=")
+ if not sep or not key:
+ print(f"error: expected key=value, got '{pair}'", file=sys.stderr)
+ return 2
+ data[key] = value
+ store.put(args.profile, data)
+ print(f"stored profile '{args.profile}' ({', '.join(sorted(data))})")
+ return 0
+
+
+SERVICE_UNIT_NAME = "openworker.service" # legacy default (pre-2026-09-02 installs)
+_UNIT_PREFIX = "openworker"
+
+
+def unit_name_for(machine_name: str) -> str:
+ """`openworker-<machine>.service` — one unit per joined identity, so two
+ installs on one box can never silently share a name (or a state dir)."""
+ slug = "".join(ch if ch.isalnum() or ch in "-_" else "-" for ch in (machine_name or "")).strip("-")
+ return f"{_UNIT_PREFIX}-{slug}.service" if slug else SERVICE_UNIT_NAME
+
+
+def _systemd_unit(state: Path, exe: str, name: str = "") -> str:
+ """A user unit running `up`: restart forever, state dir pinned explicitly so
+ the unit survives shells/relogins with a different environment."""
+ label = f" ({name})" if name else ""
+ return (
+ "[Unit]\n"
+ f"Description=OpenWorker headless (joined machine{label})\n"
+ "After=network-online.target\n"
+ "Wants=network-online.target\n"
+ "\n"
+ "[Service]\n"
+ f"ExecStart={exe} up\n"
+ f"Environment=COWORKER_STATE_DIR={state}\n"
+ "Restart=always\n"
+ "RestartSec=5\n"
+ "\n"
+ "[Install]\n"
+ "WantedBy=default.target\n"
+ )
+
+
+def installed_units(unit_dir: Path) -> list[dict]:
+ """Every openworker*.service user unit on this box with the state dir it
+ pins — what `service install` reports so a stale twin is visible, not a
+ mystery process that returns after every kill."""
+ rows = []
+ for path in sorted(unit_dir.glob(f"{_UNIT_PREFIX}*.service")):
+ state = ""
+ try:
+ for line in path.read_text().splitlines():
+ if line.startswith("Environment=COWORKER_STATE_DIR="):
+ state = line.split("=", 2)[2].strip()
+ except OSError:
+ continue
+ rows.append({"unit": path.name, "state_dir": state, "path": str(path)})
+ return rows
+
+
+def _systemctl_user(*args: str) -> bool:
+ import subprocess
+
+ try:
+ return (
+ subprocess.run(
+ ["systemctl", "--user", *args], capture_output=True, timeout=15
+ ).returncode
+ == 0
+ )
+ except (OSError, Exception):
+ return False
+
+
+def _cmd_service(state: Path, args, platform: Optional[str] = None, home: Optional[Path] = None) -> int:
+ platform = platform or sys.platform
+ home = home or Path.home()
+ if platform != "linux":
+ print(
+ "error: `service install` targets Linux/systemd (the VM/server the box "
+ "runs on). On macOS just run `openworker up` in a terminal or via launchd.",
+ file=sys.stderr,
+ )
+ return 2
+ unit_dir = home / ".config" / "systemd" / "user"
+ cfg = load_remote_config(state)
+ derived = unit_name_for(str(cfg.get("name") or "")) if cfg else SERVICE_UNIT_NAME
+ if args.service_command == "uninstall":
+ wanted = getattr(args, "unit", None) or derived
+ unit_path = unit_dir / wanted
+ if not unit_path.exists() and (unit_dir / SERVICE_UNIT_NAME).exists():
+ wanted, unit_path = SERVICE_UNIT_NAME, unit_dir / SERVICE_UNIT_NAME
+ _systemctl_user("disable", "--now", wanted)
+ unit_path.unlink(missing_ok=True)
+ _systemctl_user("daemon-reload")
+ print(f"removed {unit_path}")
+ return 0
+ if args.service_command == "list":
+ rows = installed_units(unit_dir)
+ if not rows:
+ print("no openworker units installed")
+ for row in rows:
+ print(f"{row['unit']} state={row['state_dir'] or '?'}")
+ return 0
+ if cfg is None:
+ print(
+ "error: this machine has not joined a controller yet — run "
+ "`openworker join <url>` first, then install the service.",
+ file=sys.stderr,
+ )
+ return 2
+ import shutil
+
+ # Other units on this box: a stale twin on the SAME state dir is refused
+ # (two engines, one SQLite); twins on other state dirs are reported so the
+ # operator knows a second engine will be running here.
+ others = [r for r in installed_units(unit_dir) if r["unit"] != derived]
+ same = [r for r in others if r["state_dir"] and Path(r["state_dir"]) == Path(state)]
+ if same and not getattr(args, "force", False):
+ for r in same:
+ print(
+ f"error: {r['unit']} already runs `openworker up` on this state dir "
+ f"({state}). Remove it first (`openworker service uninstall --unit "
+ f"{r['unit']}`) or pass --force to replace it.",
+ file=sys.stderr,
+ )
+ return 2
+ for r in same:
+ _systemctl_user("disable", "--now", r["unit"])
+ Path(r["path"]).unlink(missing_ok=True)
+ print(f"replaced {r['unit']}")
+ for r in others:
+ if r not in same:
+ print(
+ f"note: {r['unit']} is also installed (state {r['state_dir'] or '?'}) — "
+ "a second engine on this box; remove it if it is stale."
+ )
+
+ exe = shutil.which("openworker") or f"{sys.executable} -m coworker.cli"
+ unit_path = unit_dir / derived
+ unit_path.parent.mkdir(parents=True, exist_ok=True)
+ unit_path.write_text(_systemd_unit(state, exe, str(cfg.get("name") or "")))
+ print(f"wrote {unit_path}")
+ if _systemctl_user("daemon-reload") and _systemctl_user("enable", "--now", derived):
+ print(f"service enabled and started (systemctl --user status {derived}).")
+ print(
+ "To keep it running after logout/reboot without a login session:\n"
+ f" sudo loginctl enable-linger {__import__('getpass').getuser()}"
+ )
+ else:
+ print(
+ "systemd user session not reachable from here — enable it manually:\n"
+ " systemctl --user daemon-reload\n"
+ f" systemctl --user enable --now {derived}"
+ )
+ return 0
+
+def _cmd_status(state: Path) -> int:
+ cfg = load_remote_config(state)
+ key_path = state / KEY_FILENAME
+ print(f"state dir: {state}")
+ if key_path.exists():
+ identity = load_or_create(state)
+ print(f"identity: {identity.fingerprint} (ed25519)")
+ # The dashboard's Keys card shows this same fingerprint — comparing
+ # the two is how a user verifies a browser-sealed deploy targets THIS
+ # box and not a middlebox's substituted key.
+ print(f"sealing key: {identity.seal_fingerprint} (x25519)")
+ else:
+ print("identity: none (created on first join)")
+ if cfg is None:
+ print("controller: not joined")
+ else:
+ print(f"controller: {cfg['controller']}")
+ print(f"name: {cfg.get('name', '')}")
+ print(f"machine id: {cfg.get('machine_id', '')}")
+ return 0
+
+
+def _cmd_leave(state: Path, yes: bool) -> int:
+ cfg = load_remote_config(state)
+ key_path = state / KEY_FILENAME
+ if cfg is None and not key_path.exists():
+ print("nothing to forget — this machine never joined a controller")
+ return 0
+ if not yes:
+ answer = input(
+ "Forget enrollment AND this machine's identity? Re-joining will need a "
+ "fresh join URL. [y/N] "
+ )
+ if answer.strip().lower() not in ("y", "yes"):
+ print("aborted")
+ return 1
+ _config_path(state).unlink(missing_ok=True)
+ key_path.unlink(missing_ok=True)
+ (state / SEAL_KEY_FILENAME).unlink(missing_ok=True)
+ print("left. Remove the machine from the controller's Machines panel too.")
+ return 0
diff --git a/coworker/remote/provision.py b/coworker/remote/provision.py
new file mode 100644
index 00000000..d0f7baf3
--- /dev/null
+++ b/coworker/remote/provision.py
@@ -0,0 +1,52 @@
+"""Provisioning: every machine provenance converges on the ONE join token.
+
+BYO machine, our managed sandbox, an operator in a customer VPC — each is a
+`Provisioner` whose job is (a) mint a single-use join token and (b) optionally
+launch something that will dial in with it (remote-home-design.md §Provenances).
+Enrollment itself never varies: the box runs the existing join handshake.
+
+Desktop ships `LocalProvisioner`: minting IS arming, and there is nothing to
+launch — the user runs `openworker join` on their own hardware. Cloud adds
+Fly/operator implementations behind the same interface.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional, Protocol
+
+
+class Provisioner(Protocol):
+ def mint_token(self, spec: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ """Mint one single-use join token → {"token", "expires_at"}. A spec
+ with a "fingerprint" binds the token to that machine identity — the
+ acceptor refuses any other pubkey presenting it. A spec with an
+ "org_id" makes the enrollment land in that tenant; a "provenance"
+ {"kind", "ref"} is stamped on the enrolled row (managed sandboxes)."""
+ ...
+
+ async def launch(self, spec: dict[str, Any]) -> dict[str, Any]:
+ """Launch a machine that will join on boot (managed sandboxes and VPC
+ operators). BYO provenances raise NotImplementedError."""
+ ...
+
+
+class LocalProvisioner:
+ """Desktop: bring-your-own machines only."""
+
+ def __init__(self, acceptor) -> None:
+ self._acceptor = acceptor
+
+ def mint_token(self, spec: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ spec = spec or {}
+ token, expiry = self._acceptor.arm(
+ bound_fingerprint=str(spec.get("fingerprint") or ""),
+ org_id=str(spec.get("org_id") or ""),
+ actor=str(spec.get("actor") or ""),
+ provenance=spec.get("provenance") or None,
+ )
+ return {"token": token, "expires_at": expiry}
+
+ async def launch(self, spec: dict[str, Any]) -> dict[str, Any]:
+ raise NotImplementedError(
+ "no managed sandboxes on desktop — run `openworker join` on the machine"
+ )
diff --git a/coworker/remote/registry.py b/coworker/remote/registry.py
new file mode 100644
index 00000000..2613296b
--- /dev/null
+++ b/coworker/remote/registry.py
@@ -0,0 +1,314 @@
+"""Machines registry — the controller's durable record of enrolled boxes.
+
+Lives in coworker.db next to the other stores. Presence is deliberately NOT a
+column: liveness belongs to the acceptor's in-memory socket map, the registry
+only records identity (pinned pubkey), the user-facing name, and timestamps.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+import threading
+import time
+import uuid
+from pathlib import Path
+from typing import Any, Optional
+
+MAX_NAME_CHARS = 60
+
+
+def _clean_name(name: str) -> str:
+ cleaned = " ".join((name or "").split())[:MAX_NAME_CHARS].strip()
+ return cleaned or "machine"
+
+
+class MachinesRegistry:
+ def __init__(self, db_path: str | Path) -> None:
+ self.db_path = Path(db_path).expanduser()
+ self._lock = threading.RLock()
+ self._conn = sqlite3.connect(self.db_path, check_same_thread=False)
+ self._conn.row_factory = sqlite3.Row
+ with self._lock:
+ # Name uniqueness is PER ORG, enforced in code (enroll's suffix loop
+ # and rename's clash check) — not by a table constraint, so the
+ # desktop's org-"" world and a multi-tenant deployment share one
+ # schema. (Pre-tenancy desktop DBs carry a UNIQUE(name) constraint;
+ # harmless there — one org.)
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS machines (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ pubkey TEXT UNIQUE NOT NULL,
+ seal_pubkey TEXT DEFAULT '',
+ app_version TEXT DEFAULT '',
+ org_id TEXT NOT NULL DEFAULT '',
+ created_at REAL NOT NULL,
+ last_seen REAL
+ )
+ """
+ )
+ # Tier-2 snapshot (remote-home-design.md data path): the last-known
+ # session-LIST METADATA per machine — what keeps an offline machine's
+ # sessions greyed-but-visible instead of vanished.
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS machine_sessions (
+ machine_id TEXT PRIMARY KEY,
+ payload TEXT NOT NULL,
+ updated_at REAL NOT NULL
+ )
+ """
+ )
+ # Desktop-tier transcript cache (owner amendment 2026-08-25):
+ # cache-on-view — every transcript the user fetched while the box was
+ # connected stays readable (READ-ONLY) while it's offline. This is the
+ # DESKTOP controller only: same user, same device, same trust domain.
+ # The cloud tier never stores conversation content.
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS machine_transcripts (
+ machine_id TEXT NOT NULL,
+ session_id TEXT NOT NULL,
+ payload TEXT NOT NULL,
+ updated_at REAL NOT NULL,
+ PRIMARY KEY (machine_id, session_id)
+ )
+ """
+ )
+ # Databases from before the sealing key / tenancy (idempotent-by-
+ # error ALTERs). Pre-tenancy rows land in org "" — the desktop org.
+ for alter in (
+ "ALTER TABLE machines ADD COLUMN seal_pubkey TEXT DEFAULT ''",
+ "ALTER TABLE machines ADD COLUMN org_id TEXT NOT NULL DEFAULT ''",
+ # Fleet under the org (2026-09-02): the member who armed/approved
+ # the enrollment owns the machine in the admin's view.
+ "ALTER TABLE machines ADD COLUMN enrolled_by TEXT NOT NULL DEFAULT ''",
+ # Managed sandboxes (2026-09-02): where the machine came from
+ # ("" = brought by the user, "fly" = our sandbox) and the
+ # provisioner's own id for it, so lifecycle code can find the
+ # box a sandbox became.
+ "ALTER TABLE machines ADD COLUMN provenance TEXT NOT NULL DEFAULT ''",
+ "ALTER TABLE machines ADD COLUMN provenance_ref TEXT NOT NULL DEFAULT ''",
+ ):
+ try:
+ self._conn.execute(alter)
+ except sqlite3.OperationalError:
+ pass # already migrated
+ # Wallet deployments ledger: WHICH profiles went WHERE, with a hash
+ # of the deployed value for staleness — values themselves never
+ # flow back (remote-home-design.md §Keys wallet).
+ self._conn.execute(
+ """
+ CREATE TABLE IF NOT EXISTS machine_secret_deploys (
+ machine_id TEXT NOT NULL,
+ profile TEXT NOT NULL,
+ value_hash TEXT NOT NULL,
+ deployed_at REAL NOT NULL,
+ PRIMARY KEY (machine_id, profile)
+ )
+ """
+ )
+ self._conn.commit()
+
+ def enroll(
+ self,
+ name: str,
+ pubkey: str,
+ app_version: str = "",
+ seal_pubkey: str = "",
+ org_id: str = "",
+ enrolled_by: str = "",
+ provenance: str = "",
+ provenance_ref: str = "",
+ ) -> dict[str, Any]:
+ """Register a new pubkey in an org; collisions on the requested name
+ auto-suffix (-2, -3…) within that org. `enrolled_by` = the member who
+ armed/approved the join (the machine's owner in the org's fleet view).
+ `provenance`/`provenance_ref` = which provisioner made the machine and
+ its id there ("" for machines the user brought)."""
+ base = _clean_name(name)
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT id FROM machines WHERE pubkey = ?", (pubkey,)
+ ).fetchone()
+ if row is not None:
+ raise ValueError("pubkey already enrolled")
+ candidate, attempt = base, 1
+ while self._conn.execute(
+ "SELECT 1 FROM machines WHERE name = ? AND org_id = ?",
+ (candidate, org_id),
+ ).fetchone():
+ attempt += 1
+ candidate = f"{base}-{attempt}"
+ machine_id = uuid.uuid4().hex[:12]
+ now = time.time()
+ self._conn.execute(
+ "INSERT INTO machines (id, name, pubkey, seal_pubkey, app_version, org_id, enrolled_by,"
+ " provenance, provenance_ref, created_at, last_seen)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (machine_id, candidate, pubkey, seal_pubkey, app_version, org_id, enrolled_by,
+ provenance, provenance_ref, now, now),
+ )
+ self._conn.commit()
+ return {
+ "id": machine_id,
+ "name": candidate,
+ "pubkey": pubkey,
+ "org_id": org_id,
+ "enrolled_by": enrolled_by,
+ "provenance": provenance,
+ "provenance_ref": provenance_ref,
+ }
+
+ def by_pubkey(self, pubkey: str) -> Optional[dict[str, Any]]:
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT * FROM machines WHERE pubkey = ?", (pubkey,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def by_id(self, machine_id: str) -> Optional[dict[str, Any]]:
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT * FROM machines WHERE id = ?", (machine_id,)
+ ).fetchone()
+ return dict(row) if row else None
+
+ def list(self, org_id: Optional[str] = None) -> list[dict[str, Any]]:
+ with self._lock:
+ if org_id is None:
+ rows = self._conn.execute(
+ "SELECT * FROM machines ORDER BY created_at"
+ ).fetchall()
+ else:
+ rows = self._conn.execute(
+ "SELECT * FROM machines WHERE org_id = ? ORDER BY created_at",
+ (org_id,),
+ ).fetchall()
+ return [dict(r) for r in rows]
+
+ def touch(self, machine_id: str, app_version: str | None = None) -> None:
+ with self._lock:
+ if app_version is None:
+ self._conn.execute(
+ "UPDATE machines SET last_seen = ? WHERE id = ?",
+ (time.time(), machine_id),
+ )
+ else:
+ self._conn.execute(
+ "UPDATE machines SET last_seen = ?, app_version = ? WHERE id = ?",
+ (time.time(), app_version, machine_id),
+ )
+ self._conn.commit()
+
+ def rename(self, machine_id: str, name: str) -> Optional[dict[str, Any]]:
+ cleaned = _clean_name(name)
+ with self._lock:
+ row = self.by_id(machine_id)
+ if row is None:
+ return None
+ clash = self._conn.execute(
+ "SELECT 1 FROM machines WHERE name = ? AND org_id = ? AND id != ?",
+ (cleaned, row["org_id"], machine_id),
+ ).fetchone()
+ if clash:
+ raise ValueError(f"a machine named '{cleaned}' already exists")
+ self._conn.execute(
+ "UPDATE machines SET name = ? WHERE id = ?", (cleaned, machine_id)
+ )
+ self._conn.commit()
+ return self.by_id(machine_id)
+
+ def remove(self, machine_id: str) -> bool:
+ with self._lock:
+ cur = self._conn.execute(
+ "DELETE FROM machines WHERE id = ?", (machine_id,)
+ )
+ self._conn.execute(
+ "DELETE FROM machine_sessions WHERE machine_id = ?", (machine_id,)
+ )
+ self._conn.execute(
+ "DELETE FROM machine_transcripts WHERE machine_id = ?", (machine_id,)
+ )
+ self._conn.execute(
+ "DELETE FROM machine_secret_deploys WHERE machine_id = ?",
+ (machine_id,),
+ )
+ self._conn.commit()
+ return cur.rowcount > 0
+
+ def set_seal_pubkey(self, machine_id: str, seal_pubkey: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "UPDATE machines SET seal_pubkey = ? WHERE id = ?",
+ (seal_pubkey, machine_id),
+ )
+ self._conn.commit()
+
+ def record_deploy(self, machine_id: str, profile: str, value_hash: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "INSERT INTO machine_secret_deploys (machine_id, profile, value_hash, deployed_at)"
+ " VALUES (?, ?, ?, ?)"
+ " ON CONFLICT(machine_id, profile) DO UPDATE SET"
+ " value_hash = excluded.value_hash, deployed_at = excluded.deployed_at",
+ (machine_id, profile, value_hash, time.time()),
+ )
+ self._conn.commit()
+
+ def remove_deploy(self, machine_id: str, profile: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "DELETE FROM machine_secret_deploys WHERE machine_id = ? AND profile = ?",
+ (machine_id, profile),
+ )
+ self._conn.commit()
+
+ def deploys(self, machine_id: str) -> list[dict[str, Any]]:
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT profile, value_hash, deployed_at FROM machine_secret_deploys"
+ " WHERE machine_id = ? ORDER BY profile",
+ (machine_id,),
+ ).fetchall()
+ return [dict(r) for r in rows]
+
+ def save_sessions_snapshot(self, machine_id: str, payload: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "INSERT INTO machine_sessions (machine_id, payload, updated_at)"
+ " VALUES (?, ?, ?)"
+ " ON CONFLICT(machine_id) DO UPDATE SET payload = excluded.payload,"
+ " updated_at = excluded.updated_at",
+ (machine_id, payload, time.time()),
+ )
+ self._conn.commit()
+
+ def sessions_snapshot(self, machine_id: str) -> Optional[str]:
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT payload FROM machine_sessions WHERE machine_id = ?",
+ (machine_id,),
+ ).fetchone()
+ return row["payload"] if row else None
+
+ def save_transcript(self, machine_id: str, session_id: str, payload: str) -> None:
+ with self._lock:
+ self._conn.execute(
+ "INSERT INTO machine_transcripts (machine_id, session_id, payload, updated_at)"
+ " VALUES (?, ?, ?, ?)"
+ " ON CONFLICT(machine_id, session_id) DO UPDATE SET"
+ " payload = excluded.payload, updated_at = excluded.updated_at",
+ (machine_id, session_id, payload, time.time()),
+ )
+ self._conn.commit()
+
+ def transcript(self, machine_id: str, session_id: str) -> Optional[str]:
+ with self._lock:
+ row = self._conn.execute(
+ "SELECT payload FROM machine_transcripts"
+ " WHERE machine_id = ? AND session_id = ?",
+ (machine_id, session_id),
+ ).fetchone()
+ return row["payload"] if row else None
diff --git a/coworker/remote/service.py b/coworker/remote/service.py
new file mode 100644
index 00000000..44c3d65e
--- /dev/null
+++ b/coworker/remote/service.py
@@ -0,0 +1,181 @@
+"""The acceptor-only cloud service — the commercial tier's data plane, runnable
+today on loopback (remote-home-design.md §Cloud dashboard).
+
+This is the payoff of the acceptor-as-separate-module ruling: import the
+acceptor, add a capabilities flag, serve the SAME SPA. No engine, no sessions
+of its own, no conversation content (data-path doctrine) — machines join it,
+and every session it shows lives on a joined box, reached through the proxy.
+
+What it deliberately does NOT have:
+ - a wallet: server-side sealing would put plaintext keys in the cloud's
+ memory. Cloud key-deploy waits for BROWSER sealing (§Keys wallet tiers);
+ until then the deploy endpoints answer "no wallet configured".
+ - multi-tenant auth: the production wrapper adds identity on top; this
+ skeleton is single-tenant, gated by the same COWORKER_API_TOKEN header
+ scheme as the sidecar so the SPA's auth plumbing is exercised unchanged.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import secrets as pysecrets
+from pathlib import Path
+from typing import Any
+
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+
+from .acceptor import mount_acceptor
+from .audit import AuditLog
+from .registry import MachinesRegistry
+
+# The SPA's boot path touches a handful of desktop endpoints before it learns
+# the mode. Answer the harmless ones with honest emptiness (a cloud has no
+# LOCAL sessions/workspaces/personas) instead of 404 noise.
+_EMPTY_STUBS: dict[str, dict[str, Any]] = {
+ "/v1/sessions": {"sessions": []},
+ "/v1/workspaces/recent": {"workspaces": []},
+ "/v1/personas": {"personas": []},
+ "/v1/inbox": {"items": []},
+ "/v1/subscriptions": {"subscriptions": []},
+}
+
+
+def add_cloud_shims(app: FastAPI) -> None:
+ """The desktop-shaped endpoints an acceptor-only deployment must answer
+ for the SPA to boot cleanly — shared by this skeleton and the hosted
+ machines service, so the two cloud tiers can't drift apart."""
+
+ @app.get("/v1/settings")
+ def cloud_settings() -> dict[str, Any]:
+ # Minimal: the cloud has no models of its own — every session's models
+ # come from its machine (the machine-scoped picker).
+ return {
+ "model": "",
+ "models": [],
+ "model_labels": {},
+ "model_context_windows": {},
+ "model_ready": False,
+ "nav_layout": "machine",
+ "sessions_peek": 5,
+ "context_bar": False,
+ "surfaces": {"cowork": True, "chat": False, "code": False},
+ }
+
+ for path, payload in _EMPTY_STUBS.items():
+ def _stub(payload=payload) -> dict[str, Any]:
+ return payload
+
+ app.get(path)(_stub)
+
+ @app.websocket("/ws/events")
+ async def cloud_events(ws) -> None:
+ # The SPA keeps a global events socket open; a cloud has no local
+ # engine emitting events, but refusing the socket puts the SPA in a
+ # retry loop (and behind a StaticFiles mount the handshake 500s).
+ # Accept and stay silent until the client hangs up. Selecting the
+ # offered subprotocol matters: browsers close an unanswered offer.
+ offered = {
+ part.strip()
+ for part in ws.headers.get("sec-websocket-protocol", "").split(",")
+ if part.strip()
+ }
+ await ws.accept(subprotocol="openworker" if "openworker" in offered else None)
+ try:
+ while True:
+ await ws.receive_text()
+ except Exception:
+ pass
+
+
+def create_cloud_app(data_dir: str | Path) -> FastAPI:
+ base = Path(data_dir).expanduser()
+ base.mkdir(parents=True, exist_ok=True)
+ app = FastAPI(title="openworker-cloud", version="0.0.0")
+ api_token = os.environ.get("COWORKER_API_TOKEN", "")
+
+ def _request_authenticated(request: Request) -> bool:
+ provided = request.headers.get("x-openworker-token", "")
+ return bool(
+ api_token and provided and pysecrets.compare_digest(provided, api_token)
+ )
+
+ @app.middleware("http")
+ async def require_token(request: Request, call_next):
+ if (
+ not api_token
+ or request.method == "OPTIONS"
+ or request.url.path
+ in (
+ "/v1/health",
+ "/v1/capabilities",
+ # Machine-facing device-flow halves; approval stays gated.
+ "/v1/remote/device/start",
+ "/v1/remote/device/poll",
+ )
+ or request.url.path.startswith("/j/")
+ or _request_authenticated(request)
+ ):
+ return await call_next(request)
+ return JSONResponse({"error": "missing or invalid token"}, status_code=401)
+
+ def _ws_authenticated(ws) -> bool:
+ if not api_token:
+ return True
+ protocols = {
+ part.strip()
+ for part in ws.headers.get("sec-websocket-protocol", "").split(",")
+ if part.strip()
+ }
+ return any(pysecrets.compare_digest(part, api_token) for part in protocols)
+
+ @app.get("/v1/capabilities")
+ def capabilities() -> dict[str, Any]:
+ return {"mode": "cloud"}
+
+ @app.get("/v1/health")
+ def health() -> dict[str, Any]:
+ # Shape-compatible with the sidecar's health: the SPA's boot check
+ # passes without knowing the mode yet.
+ return {"status": "ok", "default_workspace": None, "model": ""}
+
+ add_cloud_shims(app)
+
+ mount_acceptor(
+ app,
+ MachinesRegistry(base / "cloud.db"),
+ ws_authenticated=_ws_authenticated,
+ api_token=api_token,
+ wallet=None, # cloud never holds plaintext keys; browser sealing lands later
+ audit=AuditLog(base / "remote-audit.jsonl"),
+ )
+ return app
+
+
+def main(argv=None) -> None:
+ parser = argparse.ArgumentParser(
+ prog="openworker-acceptor",
+ description="Acceptor-only cloud service: machines join it; the SPA runs against it in cloud mode.",
+ )
+ parser.add_argument("--data-dir", default="~/.config/openworker-cloud")
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=9787)
+ parser.add_argument(
+ "--spa",
+ default=None,
+ help="path to the built GUI bundle (surfaces/gui/dist) to serve at /",
+ )
+ args = parser.parse_args(argv)
+ app = create_cloud_app(args.data_dir)
+ if args.spa:
+ from fastapi.staticfiles import StaticFiles
+
+ app.mount("/", StaticFiles(directory=args.spa, html=True), name="spa")
+ import uvicorn
+
+ uvicorn.run(app, host=args.host, port=args.port, ws_max_size=16 * 2**20)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/coworker/remote/stores.py b/coworker/remote/stores.py
new file mode 100644
index 00000000..01d3ed59
--- /dev/null
+++ b/coworker/remote/stores.py
@@ -0,0 +1,200 @@
+"""Control-plane store interfaces: the seam between one desktop and a fleet.
+
+The acceptor speaks to two stores and never cares what backs them
+(remote-home-design.md §Planes — seams, not services):
+
+ - `Registry`: durable machine state — enrollments, pinned keys, deploy
+ ledger, session snapshots. Desktop default: `MachinesRegistry` (SQLite).
+ Cloud: the same interface over Postgres.
+ - `Ephemera`: shared transient state — enrollment tokens and the clone-trap
+ lease. Desktop default: `InMemoryEphemera` (a restart disarms, which is
+ the safe default). Cloud: Redis, where atomic consume/acquire make the
+ single-use token and one-connection-per-identity guarantees hold across a
+ gateway fleet.
+
+What deliberately stays OUT of `Ephemera`: the live socket map. An RpcClient
+is a process-local object — in a fleet, presence answers "which node holds the
+socket" and routing replays to that node; the map itself never leaves the
+gateway. So `_live` stays in the acceptor.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any, Optional, Protocol
+
+
+class Registry(Protocol):
+ """Durable machine state. `MachinesRegistry` is the SQLite implementation.
+
+ Tenancy: every machine belongs to an org (`org_id`); the desktop is the
+ degenerate single-tenant case where everything lives in org "". Machine
+ names are unique PER ORG. Row-level scoping is enforced by the acceptor's
+ endpoints (fetch → compare org) — `by_id`/`by_pubkey` are deliberately
+ unscoped so the enrollment handshake can find any pinned identity."""
+
+ def enroll(
+ self,
+ name: str,
+ pubkey: str,
+ app_version: str = "",
+ seal_pubkey: str = "",
+ enrolled_by: str = "",
+ org_id: str = "",
+ provenance: str = "",
+ provenance_ref: str = "",
+ ) -> dict[str, Any]: ...
+ def by_pubkey(self, pubkey: str) -> Optional[dict[str, Any]]: ...
+ def by_id(self, machine_id: str) -> Optional[dict[str, Any]]: ...
+ def list(self, org_id: Optional[str] = None) -> list[dict[str, Any]]: ...
+ def touch(self, machine_id: str, app_version: Optional[str] = None) -> None: ...
+ def rename(self, machine_id: str, name: str) -> None: ...
+ def remove(self, machine_id: str) -> None: ...
+ def set_seal_pubkey(self, machine_id: str, seal_pubkey: str) -> None: ...
+ def record_deploy(self, machine_id: str, profile: str, value_hash: str) -> None: ...
+ def remove_deploy(self, machine_id: str, profile: str) -> None: ...
+ def deploys(self, machine_id: str) -> list[dict[str, Any]]: ...
+ def save_sessions_snapshot(self, machine_id: str, payload: str) -> None: ...
+ def sessions_snapshot(self, machine_id: str) -> Optional[str]: ...
+ def save_transcript(self, machine_id: str, session_id: str, payload: str) -> None: ...
+ def transcript(self, machine_id: str, session_id: str) -> Optional[str]: ...
+
+
+class Ephemera(Protocol):
+ """Shared transient state. The operations that gate security guarantees
+ (`consume_token`, `acquire_lease`) must be atomic check-and-take in any
+ implementation — that is the whole reason this interface exists."""
+
+ def add_token(
+ self,
+ token: str,
+ expires_at: float,
+ bound_fingerprint: str = "",
+ org_id: str = "",
+ actor: str = "",
+ provenance: Optional[dict[str, str]] = None,
+ ) -> None: ...
+ def consume_token(self, token: str) -> Optional[dict[str, Any]]:
+ """Take the token if it exists and is unexpired; single-use — two
+ concurrent consumers must never both succeed. Returns None if invalid,
+ else {"fingerprint": bound fingerprint or "", "org_id": the org the
+ enrollment lands in, "actor": who armed/approved it, "provenance":
+ {"kind", "ref"} or {}} — the token is how a machine inherits its
+ tenant, its owner AND its provenance (a managed sandbox's token names
+ the sandbox it was minted for; spec §Fly sandboxes)."""
+ ...
+
+ def clear_tokens(self) -> None: ...
+ def has_tokens(self) -> bool: ...
+
+ def acquire_lease(self, pubkey: str) -> bool:
+ """Claim the one-connection-per-identity lease (clone trap). False if
+ already held anywhere in the deployment."""
+ ...
+
+ def release_lease(self, pubkey: str) -> None: ...
+
+ def refresh_lease(self, pubkey: str) -> None:
+ """Heartbeat: TTL-leased backends (Redis) extend the lease; the
+ acceptor calls this periodically for every live connection. In-memory
+ leases have no TTL — a process death releases them with the process."""
+ ...
+
+ # Device-authorization grants (`openworker auth join`): a box's pending
+ # request to be approved. Keyed by device_code (secret, box-held); looked
+ # up by user_code (short, human-typed) on the approval side.
+ def put_grant(self, grant: dict[str, Any]) -> None: ...
+ def grant_by_device_code(self, device_code: str) -> Optional[dict[str, Any]]: ...
+ def grant_by_user_code(self, user_code: str) -> Optional[dict[str, Any]]: ...
+ def update_grant(self, device_code: str, **fields: Any) -> None: ...
+ def remove_grant(self, device_code: str) -> None: ...
+ def list_grants(self) -> list[dict[str, Any]]: ...
+
+
+class InMemoryEphemera:
+ """Desktop default: one process, so plain dicts under the event loop's
+ implicit serialization are already atomic."""
+
+ def __init__(self) -> None:
+ # token -> (expiry, bound fingerprint, org, actor, provenance)
+ self._tokens: dict[str, tuple[float, str, str, str, dict[str, str]]] = {}
+ self._leases: set[str] = set()
+ self._grants: dict[str, dict[str, Any]] = {} # device_code -> grant
+
+ def add_token(
+ self,
+ token: str,
+ expires_at: float,
+ bound_fingerprint: str = "",
+ org_id: str = "",
+ actor: str = "",
+ provenance: Optional[dict[str, str]] = None,
+ ) -> None:
+ self._prune()
+ self._tokens[token] = (expires_at, bound_fingerprint, org_id, actor, dict(provenance or {}))
+
+ def consume_token(self, token: str) -> Optional[dict[str, Any]]:
+ self._prune()
+ entry = self._tokens.pop(token, None)
+ if entry is None or entry[0] <= time.time():
+ return None
+ return {
+ "fingerprint": entry[1],
+ "org_id": entry[2],
+ "actor": entry[3],
+ "provenance": dict(entry[4]),
+ }
+
+ def clear_tokens(self) -> None:
+ self._tokens.clear()
+
+ def has_tokens(self) -> bool:
+ self._prune()
+ return bool(self._tokens)
+
+ def acquire_lease(self, pubkey: str) -> bool:
+ if pubkey in self._leases:
+ return False
+ self._leases.add(pubkey)
+ return True
+
+ def release_lease(self, pubkey: str) -> None:
+ self._leases.discard(pubkey)
+
+ def refresh_lease(self, pubkey: str) -> None:
+ pass # no TTL to extend
+
+ def put_grant(self, grant: dict[str, Any]) -> None:
+ self._prune()
+ self._grants[str(grant["device_code"])] = dict(grant)
+
+ def grant_by_device_code(self, device_code: str) -> Optional[dict[str, Any]]:
+ self._prune()
+ grant = self._grants.get(device_code)
+ return dict(grant) if grant else None
+
+ def grant_by_user_code(self, user_code: str) -> Optional[dict[str, Any]]:
+ self._prune()
+ for grant in self._grants.values():
+ if grant.get("user_code") == user_code:
+ return dict(grant)
+ return None
+
+ def update_grant(self, device_code: str, **fields: Any) -> None:
+ grant = self._grants.get(device_code)
+ if grant is not None:
+ grant.update(fields)
+
+ def remove_grant(self, device_code: str) -> None:
+ self._grants.pop(device_code, None)
+
+ def list_grants(self) -> list[dict[str, Any]]:
+ self._prune()
+ return [dict(g) for g in self._grants.values()]
+
+ def _prune(self) -> None:
+ now = time.time()
+ self._tokens = {t: e for t, e in self._tokens.items() if e[0] > now}
+ self._grants = {
+ c: g for c, g in self._grants.items() if float(g.get("expires_at", 0)) > now
+ }
diff --git a/coworker/secrets.py b/coworker/secrets.py
index 00f1d994..1607cdfe 100644
--- a/coworker/secrets.py
+++ b/coworker/secrets.py
@@ -37,6 +37,11 @@ def state_dir() -> Path:
base = os.environ.get("COWORKER_STATE_DIR")
if base:
return Path(base).expanduser()
+ # A box confined to OPENWORKER_BASE_DIR keeps its state there too
+ # (coworker/basedir.py) — nothing of the machine's lives outside it.
+ confined = os.environ.get("OPENWORKER_BASE_DIR", "").strip()
+ if confined:
+ return Path(confined).expanduser() / "state"
if sys.platform == "win32":
appdata = os.environ.get("APPDATA")
if appdata:
@@ -213,3 +218,28 @@ class SecretStore:
def _write(self, store: dict[str, Any]) -> None:
_atomic_private_write(self.path, json.dumps(store, indent=2))
+
+
+class EphemeralSecretStore(SecretStore):
+ """A SecretStore that never touches disk.
+
+ Used to stage a connector grant that is destined for ANOTHER machine
+ (machines spec §Remote OAuth): the normal storage layers run against this
+ store, producing exactly the profile keys a fresh connect would write, and
+ the result is sealed and shipped — the grant never lands in the local
+ secrets file.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(path="/dev/null/ephemeral") # never read or written
+ self._data: dict[str, Any] = {}
+
+ def _read(self) -> dict[str, Any]:
+ return dict(self._data)
+
+ def _write(self, store: dict[str, Any]) -> None:
+ self._data = dict(store)
+
+ def profiles(self) -> dict[str, Any]:
+ """Every staged profile, by key — the payload a sealed deploy ships."""
+ return dict(self._data)
diff --git a/coworker/server/run.py b/coworker/server/run.py
index 6eb7842e..40cd9ac9 100644
--- a/coworker/server/run.py
+++ b/coworker/server/run.py
@@ -136,6 +136,27 @@ def _ensure_api_token(port: int) -> Path | None:
)
+_ENGINE_LOCK = None
+
+
+def _warn_if_state_shared() -> None:
+ """The desktop sidecar runs on a random port precisely so it can coexist with
+ a hand-run `openworker-server` on the same state dir, so this entrypoint only
+ WARNS about a second engine (statelock.py). `openworker up` refuses outright;
+ set COWORKER_STATE_LOCK=strict to make this server refuse too."""
+ global _ENGINE_LOCK
+ from ..statelock import EngineBusy, acquire
+
+ strict = os.environ.get("COWORKER_STATE_LOCK") == "strict"
+ try:
+ _ENGINE_LOCK = acquire(state_dir(), timeout=10.0 if strict else 0.0)
+ except EngineBusy as exc:
+ if strict:
+ print(f"error: {exc}", file=sys.stderr)
+ raise SystemExit(3)
+ print(f"warning: {exc}", file=sys.stderr)
+
+
def main(argv=None) -> None:
_ensure_ca_bundle()
cfg = load_config() # global config supplies defaults
@@ -161,6 +182,7 @@ def main(argv=None) -> None:
import uvicorn
_exit_when_orphaned()
+ _warn_if_state_shared()
app = build_app(args.cwd, args.model, args.mode)
uvicorn.run(
app, host=args.host, port=args.port, ws_max_size=_WS_MAX_FRAME_BYTES
diff --git a/coworker/statelock.py b/coworker/statelock.py
new file mode 100644
index 00000000..0d3aaf17
--- /dev/null
+++ b/coworker/statelock.py
@@ -0,0 +1,117 @@
+"""One engine per state directory.
+
+Two engines writing one state dir corrupt each other quietly: SQLite rows
+vanish behind a cached handle, boards get two writers, sessions double-wake.
+The failure we actually shipped was two systemd user units on one VM, both
+running `openworker up` (a stale `openworker.service` from the first machine
+test beside the hand-written unit) — every "kill the stray" was undone by
+`Restart=always` five seconds later. This lock makes the second engine say so
+and stop, instead of running.
+
+`acquire()` holds an advisory lock on `<state>/engine.lock` for the life of
+the returned handle (the process, in practice) and records the holder's pid
+in the file for the refusal message. POSIX uses flock; Windows uses
+msvcrt.locking on the first byte. Best effort where neither exists: the
+lock degrades to "always acquired" rather than blocking a launch.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import time
+from pathlib import Path
+from typing import Optional
+
+LOCK_NAME = "engine.lock"
+
+
+class EngineBusy(RuntimeError):
+ def __init__(self, state: Path, holder_pid: Optional[int]) -> None:
+ self.state = Path(state)
+ self.holder_pid = holder_pid
+ who = f"pid {holder_pid}" if holder_pid else "another process"
+ super().__init__(
+ f"another engine ({who}) already holds the state dir {self.state} — "
+ "two engines on one state dir corrupt it. Stop the other one first "
+ "(on a systemd box: `systemctl --user list-units 'openworker*'`)."
+ )
+
+
+class EngineLock:
+ """Handle returned by `acquire()`; keep it referenced. `release()` is for tests."""
+
+ def __init__(self, path: Path, fh) -> None:
+ self.path = path
+ self._fh = fh
+
+ def release(self) -> None:
+ fh, self._fh = self._fh, None
+ if fh is None:
+ return
+ try:
+ if sys.platform == "win32":
+ import msvcrt
+
+ fh.seek(0)
+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
+ except OSError:
+ pass
+ fh.close()
+
+
+def _try_lock(fh) -> bool:
+ try:
+ if sys.platform == "win32":
+ import msvcrt
+
+ fh.seek(0)
+ msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return True
+ except (OSError, ImportError):
+ return False
+
+
+def holder_pid(state: Path) -> Optional[int]:
+ """Pid recorded by the current holder, if any (informational only)."""
+ try:
+ text = (Path(state) / LOCK_NAME).read_text().strip()
+ return int(text) if text else None
+ except (OSError, ValueError):
+ return None
+
+
+def acquire(state: Path, *, timeout: float = 0.0) -> EngineLock:
+ """Take the engine lock for `state`, waiting up to `timeout` seconds for a
+ dying predecessor (a supervisor restarting us while the old process is
+ still tearing down). Raises `EngineBusy` when it stays held."""
+ state = Path(state)
+ state.mkdir(parents=True, exist_ok=True)
+ path = state / LOCK_NAME
+ # "a+" never truncates: the holder's pid stays readable for the message.
+ fh = open(path, "a+")
+ deadline = time.monotonic() + max(0.0, timeout)
+ while True:
+ if _try_lock(fh):
+ break
+ if time.monotonic() >= deadline:
+ pid = holder_pid(state)
+ fh.close()
+ raise EngineBusy(state, pid if pid != os.getpid() else None)
+ time.sleep(0.2)
+ try:
+ fh.seek(0)
+ fh.truncate()
+ fh.write(str(os.getpid()))
+ fh.flush()
+ except OSError:
+ pass
+ return EngineLock(path, fh)
diff --git a/docs/remote-machines.md b/docs/remote-machines.md
new file mode 100644
index 00000000..6e58c400
--- /dev/null
+++ b/docs/remote-machines.md
@@ -0,0 +1,184 @@
+# Remote machines — run OpenWorker on another computer
+
+Run the OpenWorker agent on a VM, home server, or spare machine, and control it
+from the desktop app. Sessions live on the machine and **keep running while your
+laptop is closed** — you reconnect and pick up where things stand.
+
+A few things are true by design, before any setup:
+
+- **Machines dial out to you.** A joined machine opens no ports and accepts no
+ connections — it makes one outbound connection to your desktop app and holds
+ it. There is nothing to expose, firewall, or harden on the machine.
+- **Your data stays on the machine.** Conversations run and persist on the
+ machine's own disk. The desktop shows them live while connected, and keeps a
+ read-only copy of what you've viewed for when the machine is offline.
+- **Each machine holds its own keys.** Model and connector keys you deploy are
+ copied to the machine's local store, end-to-end encrypted to that machine —
+ it works independently ever after.
+
+## What you need
+
+- The OpenWorker **desktop app** on your Mac or PC (this is the controller).
+- A **Linux machine** (Ubuntu 22.04+ or similar, x64 or ARM) with Python 3.10+.
+- A network path from the machine **to** your desktop — see
+ [Reachability](#reachability-how-the-machine-finds-your-desktop) below.
+ Tailscale is the easy answer; an SSH reverse tunnel works with nothing but
+ OpenSSH.
+
+## 1. Install on the machine
+
+On the remote machine:
+
+```bash
+sudo apt update && sudo apt install -y git curl python3-venv python3-pip
+python3 -m venv ~/ow-venv
+~/ow-venv/bin/pip install "git+https://github.com/andrewyng/openworker.git"
+```
+
+Optional but recommended, so `openworker` is on your PATH:
+
+```bash
+echo 'export PATH=$HOME/ow-venv/bin:$PATH' >> ~/.bashrc && source ~/.bashrc
+```
+
+Check it:
+
+```bash
+openworker status
+```
+
+You should see `controller: not joined` — a fresh, unenrolled machine.
+
+## Reachability: how the machine finds your desktop
+
+The machine connects to your desktop app's local server (port 8765). Your
+desktop binds to localhost only, so pick one of these:
+
+**Option A — Tailscale (recommended).** Install [Tailscale](https://tailscale.com)
+on both computers. In the desktop app, enable listening on the tailnet
+interface, and use your desktop's Tailscale address in the join URL. Survives
+reboots on both ends with no extra care.
+
+**Option B — SSH reverse tunnel (zero new software).** If you can SSH from your
+desktop to the machine, run this **on your desktop** and leave it running:
+
+```bash
+ssh -N -o ServerAliveInterval=15 -R 8765:localhost:8765 you@your-machine
+```
+
+This makes your desktop's server appear at the *machine's own*
+`localhost:8765` — the join URL from the app works exactly as displayed.
+Note: the tunnel dies if either end reboots; use `autossh` or a process
+supervisor to keep it up unattended.
+
+## 2. Enroll the machine
+
+1. In the desktop app: **Settings → Machines → “Add a machine…”**. Opening the
+ card *arms* enrollment: it mints a one-time join token valid for 10 minutes.
+2. Leave **“Provision with my model keys”** ticked if you want the machine to
+ receive your model keys the moment it joins (encrypted to the machine; see
+ [Keys](#3-give-the-machine-keys)).
+3. Copy the one-line command from the card and run it on the machine:
+
+```bash
+openworker join http://127.0.0.1:8765/j/<token> --name=my-box
+```
+
+The card flips to **“✓ my-box joined”** and shows the machine's key
+fingerprint. Verify it matches `openworker status` on the machine — that
+fingerprint is the machine's permanent identity. The token is single-use and
+already dead; reconnects authenticate with the machine's own keypair, so you
+never enroll twice.
+
+## 3. Give the machine keys
+
+The machine needs its own model key to run turns (its own keys, its own calls —
+your desktop is not in the loop at runtime). Three ways:
+
+- **At enrollment**: the “Provision with my model keys” checkbox on the card.
+- **Anytime, from the desktop**: every provider card in **Settings → Models**
+ (and key-based connector cards) shows an **“Available on”** row once a
+ machine is enrolled — click the machine's chip to deploy or remove that key.
+ If you rotate a key later, the chip shows ↻; click to redeploy.
+- **On the machine itself**, if you'd rather keys never transit anywhere:
+
+```bash
+openworker secrets set provider:openai api_key=sk-...
+```
+
+ (Or inject via environment/secret-manager — the machine's store resolves
+ `${VAR}` references.)
+
+Deployed keys are sealed to the machine's public key before they leave your
+desktop; only that machine can decrypt them. OAuth-connected accounts (Google,
+Slack, …) are *not* copied between machines — each machine connects its own.
+
+## 4. Use it
+
+- **Start a session on the machine**: in the composer's setup row, the **runs
+ on** chip appears once a machine is enrolled — pick ⌂ my-box. The model
+ picker switches to the machine's own models.
+- **Folder-based coworkers** (code work, leads): when you send, you'll be
+ asked where on the machine to work — type a path (validated by the machine
+ itself), pick one of its recent folders, or start in a temporary folder
+ created on the machine.
+- **Sidebar**: remote sessions wear a quiet ⌂ badge; the RECENT header's
+ group-and-filter popover gains a **Machine** grouping.
+- **Inbox**: approvals and questions parked by sessions on any connected
+ machine appear in your desktop Inbox, tagged with the machine — answer them
+ from your chair.
+- **Machine offline?** Its sessions stay listed (greyed). Conversations you
+ had opened remain readable, read-only, with a banner; new messages and
+ approvals wait for the machine to return. It reconnects on its own.
+
+## 5. Run it as a service
+
+To keep the machine serving across logouts and reboots, on the machine:
+
+```bash
+openworker service install
+```
+
+This writes and enables a systemd user unit running `openworker up`
+(auto-restart, 5s backoff). To also run without anyone logged in:
+
+```bash
+sudo loginctl enable-linger $USER
+```
+
+`openworker service uninstall` reverses it. (If you used the SSH-tunnel
+option, remember the tunnel on your desktop needs the same treatment —
+`autossh` or a LaunchAgent — or the machine will wait patiently for a tunnel
+that isn't there.)
+
+## Security model, in five lines
+
+- The machine only dials **out**; it listens on nothing.
+- First contact is authorized by a **single-use token** you minted seconds
+ earlier; every reconnect is a challenge signed by the machine's private key.
+- The controller **pins** the machine's public keys at enrollment and refuses
+ a second concurrent connection claiming the same identity.
+- Secrets you deploy are **encrypted to the machine** before leaving your
+ desktop.
+- Conversation content lives on the machine; your desktop caches only what
+ you've viewed, and only for offline reading.
+
+One more thing worth knowing: signing in to OpenWorker Cloud never changes
+what's on this computer. Your conversations, keys, and enrolled machines
+belong to this computer's user account; sign-in only adds cloud machines
+and cloud features on top, and signing out hides only those.
+
+## Troubleshooting
+
+| Symptom | Likely cause |
+|---|---|
+| `join` says `not-enrolled` | Token expired (10 min) or already used — reopen the Add-a-machine card for a fresh URL. |
+| `join` says `already-connected` | Another process holds this machine's identity (a copied state dir, or a service already running). One identity, one connection. |
+| `join` says `protocol-mismatch` | Desktop and machine versions differ too much — update the older side. |
+| Machine shows offline after its reboot | The service reconnects by itself within seconds — if it doesn't, an SSH tunnel on the desktop probably died with it. |
+| Turn fails with a key error | The machine resolves models with **its** keys — deploy one (§3) or check the machine's model settings via the session's model picker. |
+
+State on the machine lives in `~/.config/coworker` (identity keys, secrets,
+conversations). `openworker leave` forgets the enrollment *and* the identity —
+re-joining afterwards needs a fresh join URL, and the old entry can be removed
+from the desktop's Machines page.
diff --git a/pyproject.toml b/pyproject.toml
index 96f626d1..3c18c63a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -23,7 +23,8 @@ dependencies = [
"pydantic>=2",
"mcp>=1.28.1,<2", # MCP client (stdio + streamable-http); floor >=1.28.1 avoids PYSEC-2026-3481/3482/3483 (fixed in 1.27.2/1.28.1); <2 since 2.0.0 removed streamablehttp_client
"httpx>=0.27", # sync outbound senders for messaging connectors (send_message tool)
- "websockets>=13", # managed Slack relay client transport (relay_client.py)
+ "websockets>=13", # managed Slack relay client transport (relay_client.py) + remote-home joiner
+ "cryptography>=42", # ed25519 machine identity for remote homes (already transitive via google-auth)
"ddgs>=9", # keyless default web-search provider (DuckDuckGo); Tavily/Brave use httpx
"croniter>=2", # cron next-fire math for the automation scheduler
# PDF attachments for models without native PDF support (pdf_support.py):
@@ -53,6 +54,7 @@ bedrock = ["boto3>=1.34"]
openworker = "coworker.cli:main"
openworker-server = "coworker.server.run:main"
openworker-connectors = "coworker.connectors.cli:main"
+openworker-acceptor = "coworker.remote.service:main"
# The board as an open surface (OPE-100): `ocw board …` / `ocw journal …`,
# including `ocw board mcp` — the stdio MCP server external harnesses attach to.
ocw = "coworker.teams.cli:main"
diff --git a/tests/test_audit_export.py b/tests/test_audit_export.py
new file mode 100644
index 00000000..d93b7d9a
--- /dev/null
+++ b/tests/test_audit_export.py
@@ -0,0 +1,491 @@
+"""Audit export (remote/audit_export.py): off by default, policy-driven, content-blind."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+
+import pytest
+
+from coworker.audit import AuditStore
+from coworker.remote.audit_export import (
+ AuditExporter,
+ ExportPolicy,
+ load_policy,
+ save_policy,
+ to_ocsf,
+)
+
+
+def _row_event(i=0, **over):
+ return {
+ "session_id": "s1",
+ "agent": "cowork",
+ "workspace": "/Users/x/proj",
+ "tool": "github_open_pr",
+ "stage": "tool_call",
+ "status": "ok",
+ "approval": "allow",
+ "arguments": {"directory": "/Users/x/proj", "title": f"PR {i}", "token": "sk-secret"},
+ "result_preview": "THE PR BODY — content, must never leave",
+ "reason": "the model's reasoning — content, must never leave",
+ "resource": "acme/api#12",
+ "call_id": f"c{i}",
+ "tokens_in": 10,
+ "tokens_out": 5,
+ **over,
+ }
+
+
+# -- policy ---------------------------------------------------------------------
+
+
+def test_policy_is_off_by_default_and_never_on_by_accident():
+ assert ExportPolicy.from_policy(None).enabled is False
+ assert ExportPolicy.from_policy({}).enabled is False
+ assert ExportPolicy.from_policy({"audit_export": "yes"}).enabled is False
+ assert ExportPolicy.from_policy({"audit_export": {"enabled": False}}).enabled is False
+ # http sink needs a real URL, otherwise OFF.
+ assert ExportPolicy.from_policy({"audit_export": {"enabled": True, "sink": "http"}}).enabled is False
+ assert ExportPolicy.from_policy({"audit_export": {"enabled": True, "sink": "ftp"}}).enabled is False
+
+
+def test_policy_parses_cloud_and_http_sinks():
+ cloud = ExportPolicy.from_policy({"audit_export": {"enabled": True}})
+ assert cloud.enabled and cloud.sink == "cloud" and cloud.batch == 200
+ http = ExportPolicy.from_policy(
+ {
+ "audit_export": {
+ "enabled": True,
+ "sink": "http",
+ "url": "https://siem.example/hec",
+ "headers": {"Authorization": "Splunk x"},
+ "batch": 5000,
+ "flush_seconds": 0.1,
+ }
+ }
+ )
+ assert http.sink == "http" and http.url == "https://siem.example/hec"
+ assert http.headers == {"Authorization": "Splunk x"}
+ assert http.batch == 1000 and http.flush_seconds == 1.0 # clamped
+
+
+def test_policy_record_persists_for_visible_governance(tmp_path):
+ save_policy(tmp_path, {"audit_export": {"enabled": True}, "org_id": "org-1"})
+ stored = load_policy(tmp_path)
+ assert stored["audit_export"] == {"enabled": True} and stored["org_id"] == "org-1"
+ assert "received_at" in stored
+ assert load_policy(tmp_path / "missing") == {}
+
+
+# -- OCSF mapping ------------------------------------------------------------------
+
+
+def test_to_ocsf_is_content_blind(tmp_path):
+ store = AuditStore(tmp_path / "a.db")
+ store.append(_row_event())
+ row = store.list_since(0)[0]
+ ev = to_ocsf(row, machine_id="m1", machine_name="cloud-vm", org_id="org-1")
+ flat = json.dumps(ev)
+ assert "THE PR BODY" not in flat and "reasoning" not in flat
+ assert "sk-secret" not in flat # the local store already stripped it
+ assert ev["class_uid"] == 6003 and ev["category_uid"] == 6 and ev["type_uid"] == 600399
+ assert ev["api"] == {"operation": "github_open_pr", "service": {"name": "github"}}
+ # No controller-verified login on this row → automated; the persona rides unmapped.
+ assert ev["actor"]["user"] == {"name": "", "org": {"uid": "org-1"}}
+ assert ev["unmapped"]["agent"] == "cowork" and ev["unmapped"]["automated"] is True
+ assert ev["actor"]["session"] == {"uid": "s1"}
+ store.append(_row_event(1, actor="[email protected]"))
+ who = to_ocsf(store.list_since(1)[0], org_id="org-1")
+ assert who["actor"]["user"] == {"name": "[email protected]", "email_addr": "[email protected]", "org": {"uid": "org-1"}}
+ assert who["unmapped"]["automated"] is False
+ assert ev["device"] == {"uid": "m1", "name": "cloud-vm"}
+ assert ev["unmapped"]["workspace"] == "proj" # basename only
+ assert ev["unmapped"]["tokens_in"] == 10 and ev["unmapped"]["tokens_out"] == 5
+ assert ev["unmapped"]["approval"] == "allow"
+ assert isinstance(ev["unmapped"]["resource"], str) # store-derived, never content
+ assert ev["status_id"] == 1 and ev["metadata"]["uid"] == f"m1:{row['id']}"
+ assert isinstance(ev["time"], int) and ev["time"] > 1_600_000_000_000
+ store.close()
+
+
+def test_store_cursor_read_and_subscribe(tmp_path):
+ store = AuditStore(tmp_path / "a.db")
+ seen = []
+ store.subscribe(seen.append)
+ for i in range(3):
+ store.append(_row_event(i))
+ assert seen == [1, 2, 3]
+ assert [r["id"] for r in store.list_since(0)] == [1, 2, 3]
+ assert [r["id"] for r in store.list_since(2)] == [3]
+ assert store.list_since(1, limit=1)[0]["args"]["title"] == "PR 1"
+ store.close()
+
+
+# -- the emitter -------------------------------------------------------------------
+
+
+def test_flush_advances_cursor_only_on_ack(tmp_path):
+ store = AuditStore(tmp_path / "a.db")
+ for i in range(5):
+ store.append(_row_event(i))
+ policy = ExportPolicy.from_policy({"audit_export": {"enabled": True, "batch": 2}})
+ exp = AuditExporter(tmp_path, store, machine_id="m1", policy=policy)
+ batches = []
+
+ async def ok(events):
+ batches.append([e["unmapped"]["row_id"] for e in events])
+ return True
+
+ assert asyncio.run(exp.flush_once(ok)) == 5
+ assert batches == [[1, 2], [3, 4], [5]]
+ assert exp.status()["last_id"] == 5 and exp.status()["exported"] == 5
+ assert json.loads((tmp_path / "audit-export.json").read_text())["last_id"] == 5
+
+ # New rows, sink refuses: cursor stays, error recorded, nothing skipped.
+ store.append(_row_event(6))
+
+ async def refuse(events):
+ return False
+
+ with pytest.raises(ConnectionError):
+ asyncio.run(exp.flush_once(refuse))
+ assert exp.status()["last_id"] == 5 and "refused" in exp.status()["last_error"]
+ assert exp.status()["pending"] == 1
+ # A fresh exporter over the same state resumes from the persisted cursor.
+ again = AuditExporter(tmp_path, store, machine_id="m1", policy=policy)
+ assert asyncio.run(again.flush_once(ok)) == 1 and batches[-1] == [6]
+ store.close()
+
+
+def test_run_idles_while_off_and_ships_when_turned_on(tmp_path):
+ store = AuditStore(tmp_path / "a.db")
+ exp = AuditExporter(tmp_path, store, machine_id="m1") # policy off
+ sent = []
+
+ async def sink(events):
+ sent.extend(events)
+ return True
+
+ async def scenario():
+ task = asyncio.create_task(exp.run(sink))
+ store.append(_row_event(0))
+ await asyncio.sleep(0.2)
+ assert sent == [] # off: nothing leaves
+ exp.set_policy(ExportPolicy.from_policy({"audit_export": {"enabled": True, "flush_seconds": 1}}))
+ for _ in range(50):
+ if sent:
+ break
+ await asyncio.sleep(0.05)
+ assert len(sent) == 1
+ store.append(_row_event(1)) # the append wakes the loop
+ for _ in range(50):
+ if len(sent) == 2:
+ break
+ await asyncio.sleep(0.05)
+ assert len(sent) == 2
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ asyncio.run(scenario())
+ assert exp.status()["enabled"] is True and exp.status()["sink"] == "cloud"
+ store.close()
+
+
+def test_channel_sender_resolves_on_ack(tmp_path):
+ store = AuditStore(tmp_path / "a.db")
+ exp = AuditExporter(tmp_path, store)
+ frames = []
+
+ async def send_frame(frame):
+ frames.append(frame)
+ # The controller answers out of band; simulate it.
+ asyncio.get_running_loop().call_soon(
+ exp.ack, {"type": "audit_ack", "id": frame["id"], "accepted": True}
+ )
+
+ send = exp.channel_sender(send_frame)
+ assert asyncio.run(send([{"x": 1}])) is True
+ assert frames[0]["type"] == "audit" and frames[0]["events"] == [{"x": 1}]
+
+ async def send_frame_refused(frame):
+ asyncio.get_running_loop().call_soon(
+ exp.ack, {"type": "audit_ack", "id": frame["id"], "accepted": False}
+ )
+
+ assert asyncio.run(exp.channel_sender(send_frame_refused)([{"x": 2}])) is False
+ store.close()
+
+
+# -- the channel round trip: welcome policy → box exports → controller sink → push off
+
+
+class _Server:
+ """The real controller app under real uvicorn on an ephemeral port."""
+
+ def __init__(self, app):
+ import uvicorn
+
+ self._config = uvicorn.Config(app, host="127.0.0.1", port=0, log_level="error")
+ self._server = uvicorn.Server(self._config)
+ self._task = None
+
+ async def __aenter__(self):
+ self._task = asyncio.create_task(self._server.serve())
+ while not self._server.started:
+ await asyncio.sleep(0.01)
+ port = self._server.servers[0].sockets[0].getsockname()[1]
+ self.base = f"http://127.0.0.1:{port}"
+ return self
+
+ async def __aexit__(self, *exc):
+ self._server.should_exit = True
+ await self._task
+
+
+async def test_policy_rides_welcome_and_audit_batches_reach_the_sink(tmp_path):
+ import httpx
+
+ from coworker.remote.joiner import parse_join_url, run_joined
+ from coworker.server.app import create_app
+ from coworker.server.manager import SessionManager
+
+ ctrl = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ received: list[tuple[str, list]] = []
+ accept = {"ok": True}
+
+ def policy_for(machine_id, known):
+ return {"org_id": "org-1", "version": 1, "audit_export": {"enabled": True, "flush_seconds": 1}}
+
+ async def audit_sink(machine_id, known, events):
+ received.append((machine_id, events))
+ return accept["ok"]
+
+ ctrl.policy_for = policy_for
+ ctrl.audit_sink = audit_sink
+ ctrl_app = create_app(ctrl)
+ box = SessionManager(data_dir=tmp_path / "box-data")
+ box_app = create_app(box)
+ async with _Server(ctrl_app) as server:
+ async with httpx.AsyncClient() as client:
+ join_url = (await client.post(f"{server.base}/v1/remote/arm")).json()["join_url"]
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "box-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="cloud-vm",
+ token=token,
+ app=box_app,
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ for _ in range(100):
+ if getattr(box, "org_policy", None):
+ break
+ await asyncio.sleep(0.05)
+ # The welcome carried the org policy: persisted + applied + visible.
+ assert box.org_policy["org_id"] == "org-1"
+ assert load_policy(state)["audit_export"]["enabled"] is True
+ assert box.get_settings()["audit_export"]["enabled"] is True
+ assert box.get_settings()["audit_export"]["sink"] == "cloud"
+
+ # A tool call on the box → one OCSF event at the controller's sink.
+ box.audit_store.append(_row_event(1, session_id="sess-9"))
+ for _ in range(100):
+ if received:
+ break
+ await asyncio.sleep(0.05)
+ machine_id, events = received[0]
+ assert len(events) == 1 and events[0]["class_uid"] == 6003
+ assert events[0]["device"]["uid"] == machine_id and events[0]["device"]["name"] == "cloud-vm"
+ assert events[0]["actor"]["user"]["org"] == {"uid": "org-1"}
+ assert events[0]["actor"]["session"] == {"uid": "sess-9"}
+ assert "THE PR BODY" not in json.dumps(events)
+ assert box.audit_exporter.status()["exported"] == 1
+
+ # A refusing sink: the cursor holds and the row is retried, not lost.
+ accept["ok"] = False
+ box.audit_store.append(_row_event(2))
+ for _ in range(100):
+ if len(received) >= 2:
+ break
+ await asyncio.sleep(0.05)
+ assert box.audit_exporter.status()["last_id"] == 1
+ accept["ok"] = True
+ for _ in range(200):
+ if box.audit_exporter.status()["last_id"] == 2:
+ break
+ await asyncio.sleep(0.05)
+ assert box.audit_exporter.status()["last_id"] == 2
+
+ # Governance flips it off: the send lands, the record updates, exports stop.
+ status, body = await ctrl_app.state.remote_acceptor.push_policy(
+ machine_id, {"org_id": "org-1", "version": 2, "audit_export": {"enabled": False}}
+ )
+ assert status == 200 and body["ok"] is True and body["applied"] is True and body["version"] == 2
+ assert box.get_settings()["audit_export"]["enabled"] is False
+ assert load_policy(state)["audit_export"] == {"enabled": False}
+ before = len(received)
+ box.audit_store.append(_row_event(3))
+ await asyncio.sleep(0.4)
+ assert len(received) == before
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_desktop_controller_sends_no_policy_and_refuses_audit(tmp_path):
+ """A desktop (OSS) controller has no policy and no sink: the box keeps its
+ stored record (off), and an audit frame is answered accepted=false."""
+ import httpx
+
+ from coworker.remote.joiner import parse_join_url, run_joined
+ from coworker.server.app import create_app
+ from coworker.server.manager import SessionManager
+
+ ctrl = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ ctrl_app = create_app(ctrl)
+ box = SessionManager(data_dir=tmp_path / "box-data")
+ box_app = create_app(box)
+ async with _Server(ctrl_app) as server:
+ async with httpx.AsyncClient() as client:
+ join_url = (await client.post(f"{server.base}/v1/remote/arm")).json()["join_url"]
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "box-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(state=state, controller=server.base, name="lap", token=token,
+ app=box_app, once=True, log=lambda *_: None)
+ )
+ try:
+ for _ in range(100):
+ if getattr(box, "audit_exporter", None) is not None:
+ break
+ await asyncio.sleep(0.05)
+ assert box.get_settings()["audit_export"]["enabled"] is False
+ assert load_policy(state) == {}
+ box.audit_store.append(_row_event(1))
+ await asyncio.sleep(0.3)
+ assert box.audit_exporter.status()["exported"] == 0
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+# -- versioned documents (spec §Versioned org policy) ----------------------------
+
+
+def test_apply_policy_ignores_older_versions_and_reports(tmp_path):
+ from types import SimpleNamespace
+
+ from coworker.remote.joiner import apply_policy, held_policy, policy_version
+
+ manager = SimpleNamespace(org_policy=None)
+ app = SimpleNamespace(state=SimpleNamespace(manager=manager))
+ assert apply_policy(app, {"version": 3, "audit_export": {"enabled": True}}, state=tmp_path) == (True, 3)
+ assert policy_version(held_policy(app)) == 3
+ # Older: ignored, held version unchanged, file untouched.
+ assert apply_policy(app, {"version": 2}, state=tmp_path) == (False, 3)
+ assert load_policy(tmp_path)["version"] == 3
+ # Same version re-sent (welcome after reconnect): applied idempotently.
+ assert apply_policy(app, {"version": 3, "audit_export": {"enabled": False}}, state=tmp_path) == (True, 3)
+ assert held_policy(app)["audit_export"] == {"enabled": False}
+ # Unversioned documents (desktop controllers, tests) always apply.
+ assert apply_policy(app, {"audit_export": {"enabled": True}}, state=tmp_path) == (True, 0)
+
+
+async def test_box_checks_every_interval_and_controller_records_status(tmp_path, monkeypatch):
+ """The box asks with the version it holds; the controller records what the
+ box SAYS (checked / applied), answers current or the newer document; an
+ admin minting v2 reaches the box within one check without any push."""
+ import httpx
+
+ from coworker.remote import joiner
+ from coworker.remote.joiner import parse_join_url, run_joined
+ from coworker.server.app import create_app
+ from coworker.server.manager import SessionManager
+
+ monkeypatch.setattr(joiner, "POLICY_CHECK_SECONDS", 0.3)
+ current = {"doc": {"org_id": "org-1", "version": 1, "audit_export": {"enabled": False}}}
+ status_log: list[tuple[int, str]] = []
+ ctrl = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ ctrl.policy_for = lambda mid, known: current["doc"]
+ ctrl.policy_status = lambda mid, known, version, outcome: status_log.append((version, outcome))
+ ctrl_app = create_app(ctrl)
+ box = SessionManager(data_dir=tmp_path / "box-data")
+ box_app = create_app(box)
+ async with _Server(ctrl_app) as server:
+ async with httpx.AsyncClient() as client:
+ join_url = (await client.post(f"{server.base}/v1/remote/arm")).json()["join_url"]
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "box-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(state=state, controller=server.base, name="vm", token=token,
+ app=box_app, once=True, log=lambda *_: None)
+ )
+ try:
+ for _ in range(100):
+ if getattr(box, "org_policy", None):
+ break
+ await asyncio.sleep(0.05)
+ assert box.org_policy["version"] == 1
+ # First check: reports v1, nothing newer → "checked" only.
+ for _ in range(100):
+ if (1, "checked") in status_log:
+ break
+ await asyncio.sleep(0.05)
+ assert (1, "checked") in status_log and not any(o == "applied" for _, o in status_log)
+ # Admin mints v2. No push: the next check carries it down.
+ current["doc"] = {"org_id": "org-1", "version": 2, "audit_export": {"enabled": True, "flush_seconds": 1}}
+ for _ in range(200):
+ if (2, "applied") in status_log:
+ break
+ await asyncio.sleep(0.05)
+ assert (2, "applied") in status_log
+ assert box.org_policy["version"] == 2
+ assert load_policy(state)["version"] == 2
+ assert box.get_settings()["org_policy"]["version"] == 2
+ assert box.get_settings()["audit_export"]["enabled"] is True
+ # Subsequent checks report v2.
+ for _ in range(200):
+ if (2, "checked") in status_log:
+ break
+ await asyncio.sleep(0.05)
+ assert (2, "checked") in status_log
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+def test_approver_is_stamped_on_the_gated_tool_row(tmp_path):
+ """The Inbox item that gated a tool call records who decided; the audit row
+ of that call (joined by call id) carries `approved_by`, and so does OCSF."""
+ from coworker.inbox import InboxStore
+ from coworker.server.manager import SessionManager
+
+ m = SessionManager(data_dir=tmp_path / "d")
+ assert isinstance(m.inbox, InboxStore)
+ item = m.inbox.add_approval("s1", "Run `github_push`?", tool_call_id="call_77")
+ assert m.inbox.resolve(item.id, "allow", by="[email protected]")
+ assert m.inbox.get(item.id).resolved_by == "[email protected]"
+ assert m.inbox.resolver_of("s1", "call_77") == "[email protected]"
+ assert m.inbox.resolver_of("s1", "call_nope") == ""
+ m.note_session_actor("s1", "[email protected]")
+ m._audit_sink_for("s1")({"session_id": "s1", "tool": "github_push", "arguments": {}, "call_id": "call_77", "approval": "allow", "status": "ok"})
+ row = m.audit_store.list(session_id="s1")[0]
+ assert row["actor"] == "[email protected]" and row["approved_by"] == "[email protected]"
+ ev = to_ocsf(row)
+ assert ev["unmapped"]["approved_by"] == "[email protected]" and ev["unmapped"]["approval"] == "allow"
+ # A second resolve is a no-op and never rewrites the decider.
+ assert m.inbox.resolve(item.id, "deny", by="someone") is False
+ assert m.inbox.get(item.id).resolved_by == "[email protected]"
diff --git a/tests/test_base_dir.py b/tests/test_base_dir.py
new file mode 100644
index 00000000..0d689474
--- /dev/null
+++ b/tests/test_base_dir.py
@@ -0,0 +1,148 @@
+"""OPENWORKER_BASE_DIR (spec §Fly sandboxes, "Base directory"): a confined box
+keeps state and scratch under the base and refuses folders outside it with a
+plain error; an unconfined box behaves exactly as before."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from coworker.basedir import OutsideBaseDir, base_dir, ensure_under_base
+from coworker.secrets import state_dir
+from coworker.server.manager import SessionManager
+
+
+def test_unconfined_is_a_no_op(tmp_path, monkeypatch):
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ assert base_dir() is None
+ assert ensure_under_base(tmp_path / "anywhere") == (tmp_path / "anywhere").resolve()
+
+
+def test_confined_paths_resolve_under_base_and_outsiders_are_refused(tmp_path, monkeypatch):
+ base = tmp_path / "data"
+ (base / "proj").mkdir(parents=True)
+ outside = tmp_path / "elsewhere"
+ outside.mkdir()
+ monkeypatch.setenv("OPENWORKER_BASE_DIR", str(base))
+ assert ensure_under_base(base) == base.resolve()
+ assert ensure_under_base(base / "proj") == (base / "proj").resolve()
+ with pytest.raises(OutsideBaseDir) as exc:
+ ensure_under_base(outside, "folder")
+ assert str(base.resolve()) in str(exc.value) and "folder" in str(exc.value)
+ # A symlink inside the base pointing out does not slip through.
+ link = base / "escape"
+ link.symlink_to(outside)
+ with pytest.raises(OutsideBaseDir):
+ ensure_under_base(link)
+ # `..` tricks neither.
+ with pytest.raises(OutsideBaseDir):
+ ensure_under_base(base / ".." / "elsewhere")
+
+
+def test_state_dir_defaults_under_the_base(tmp_path, monkeypatch):
+ monkeypatch.delenv("COWORKER_STATE_DIR", raising=False)
+ monkeypatch.setenv("OPENWORKER_BASE_DIR", str(tmp_path / "data"))
+ assert state_dir() == tmp_path / "data" / "state"
+ # An explicit state dir still wins (the image sets both, consistently).
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "explicit"))
+ assert state_dir() == tmp_path / "explicit"
+
+
+def test_manager_confines_workspaces_scratch_and_roots(tmp_path, monkeypatch):
+ base = tmp_path / "data"
+ inside = base / "repo"
+ inside.mkdir(parents=True)
+ outside = tmp_path / "home-project"
+ outside.mkdir()
+ monkeypatch.setenv("OPENWORKER_BASE_DIR", str(base))
+ monkeypatch.delenv("COWORKER_SCRATCH_BASE", raising=False)
+ manager = SessionManager(data_dir=tmp_path / "mgr")
+
+ assert manager.open_workspace(str(inside))["ok"] is True
+ refused = manager.open_workspace(str(outside))
+ assert refused["ok"] is False and "only works under" in refused["error"]
+ # Creating a new folder outside is refused before anything is made.
+ assert manager.open_workspace(str(tmp_path / "new-one"), create=True)["ok"] is False
+ assert not (tmp_path / "new-one").exists()
+
+ assert manager.resolve_workspace(str(inside)) == str(inside.resolve())
+ assert manager.resolve_workspace(str(outside)) is None
+
+ # Scratch lives under the base, and a stray pref cannot move it out.
+ assert manager.scratch_base() == (base / "workspaces").resolve()
+ manager._prefs["scratch_base"] = str(outside)
+ assert manager.scratch_base() == (base / "workspaces").resolve()
+ scratch = Path(manager._provision_scratch("s-confined"))
+ assert scratch.is_relative_to(base.resolve())
+
+ assert "only works under" in manager.add_root("s-confined", str(outside))["error"]
+ assert "only works under" in manager.promote_workspace("s-confined", str(outside))["error"]
+ assert "only works under" in manager.save_temp_as_project("s-confined", str(outside / "saved"))["error"]
+
+
+def test_unconfined_manager_accepts_any_folder(tmp_path, monkeypatch):
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ anywhere = tmp_path / "anywhere"
+ anywhere.mkdir()
+ manager = SessionManager(data_dir=tmp_path / "mgr")
+ assert manager.open_workspace(str(anywhere))["ok"] is True
+
+
+def test_deployed_provider_key_adopts_a_runnable_default(tmp_path, monkeypatch):
+ """A fresh box defaults to a model nobody can run; the first provider key
+ that arrives (by deploy, not just Settings) makes its recommended model
+ the default — a working default is never stolen."""
+ monkeypatch.delenv("OPENWORKER_BASE_DIR", raising=False)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ manager = SessionManager(data_dir=tmp_path / "mgr")
+ from coworker.secrets import SecretStore
+
+ manager.secrets = SecretStore(tmp_path / "secrets.json")
+ assert manager.get_settings()["model_ready"] is False
+ # The deploy path writes the profile then calls adopt — same as the joiner.
+ manager.secrets.put("provider:anthropic", {"api_key": "sk-ant-test"})
+ adopted = manager.adopt_provider_default("anthropic")
+ assert adopted and adopted.startswith("anthropic:")
+ s = manager.get_settings()
+ assert s["model"] == adopted and s["model_ready"] is True
+ # A second key does not steal a working default.
+ manager.secrets.put("provider:openai", {"api_key": "sk-test"})
+ assert manager.adopt_provider_default("openai") is None
+ assert manager.get_settings()["model"] == adopted
+
+
+# -- store_managed_grant_bundle: the ONE staging routine (desktop + box) ------
+
+
+def test_managed_grant_bundle_handles_every_family(tmp_path):
+ from coworker.connectors.setup import store_managed_grant_bundle
+ from coworker.secrets import SecretStore
+
+ grant = {"user_id": "usr_1", "machine_credential": "mc_1"}
+ # Generic (Notion-style, multi-account layer): stamps ride the profile.
+ s = SecretStore(tmp_path / "a.json")
+ out = store_managed_grant_bundle(s, "notion", {"provider": "notion", "connector": "notion", "connection_id": "conn_n", "access_token": "tok", "account": "Acme", "account_id": "ws_1"}, grant)
+ assert out.get("ok"), out
+ prof = s.get("notion:account:ws_1") or {}
+ assert prof["access_token"] == "tok" and prof["broker_user_id"] == "usr_1" and prof["machine_credential"] == "mc_1"
+ assert store_managed_grant_bundle(s, "notion", {"connector": "notion"}, grant)["ok"] is False
+ # GitHub: one profile per installation + pointer, all stamped, no tokens.
+ s = SecretStore(tmp_path / "b.json")
+ import json as _json
+ out = store_managed_grant_bundle(s, "github", {"connection_id": "conn_g", "installation_id": "1", "account_login": "a", "account_type": "User", "repo_selection": "all", "github_login": "me", "installations": _json.dumps([{"installation_id": "1", "account_login": "a", "account_type": "User", "repo_selection": "all"}, {"installation_id": "2", "account_login": "org", "account_type": "Organization", "repo_selection": "selected"}])}, grant)
+ assert out.get("ok"), out
+ for key in ("github:install:1", "github:install:2"):
+ p = s.get(key) or {}
+ assert p["connection_id"] == "conn_g" and p["broker_user_id"] == "usr_1" and p["machine_credential"] == "mc_1"
+ assert "access_token" not in p
+ assert (s.get("github:default") or {}).get("machine_credential") == "mc_1"
+ assert store_managed_grant_bundle(s, "github", {"connection_id": "x"}, grant)["ok"] is False
+ # Slack: per-workspace bot token + pointer, stamped.
+ s = SecretStore(tmp_path / "c.json")
+ out = store_managed_grant_bundle(s, "slack", {"connection_id": "conn_s", "access_token": "xoxb-1", "team_id": "T1", "team_domain": "acme", "bot_user_id": "B1", "slack_user_id": "U1", "account": "Acme"}, grant)
+ assert out.get("ok"), out
+ p = s.get("slack:team:T1") or {}
+ assert p.get("bot_token", p.get("access_token")) and p["machine_credential"] == "mc_1" and p["connection_id"] == "conn_s"
+ assert (s.get("slack:default") or {}).get("broker_user_id") == "usr_1"
diff --git a/tests/test_cloud.py b/tests/test_cloud.py
index c1a10691..48714a16 100644
--- a/tests/test_cloud.py
+++ b/tests/test_cloud.py
@@ -480,7 +480,9 @@ You are the Sales Coworker."""
assert out["card"]["pitch_markdown"] == "**pitch**"
caps = out["capabilities"]
assert caps["tools"] == ["files", "search", "todo"]
- assert caps["messaging"] is True
+ # `messaging: true` decides nothing (spec §11): the legacy `connectors: true` grants
+ # the recommended connectors (hubspot), none of which is a chat platform.
+ assert caps["messaging"] is False and caps["connectors"] == ["hubspot"]
assert out["recommends"] == [
{"kind": "connector", "ref": "hubspot", "reason": "read deals", "tier": "core"}
]
@@ -496,3 +498,80 @@ def test_gallery_detail_rejects_malformed_manifest(secrets, config, monkeypatch)
out = cloud.gallery_detail(secrets, config, "bad")
assert not out["ok"]
assert "validation" in out["error"]
+
+
+# --- delegated (machine-held) renewal — machines spec §Remote OAuth ------------
+
+
+def test_refresh_managed_token_delegated_fallback(secrets, config, monkeypatch):
+ """No cloud session (a box): a delegated managed profile renews by
+ possession on the delegated route — no Authorization header, opaque
+ user_id in the body. The renewed tokens land back in the profile."""
+ secrets.put(
+ "notion:default",
+ {
+ "managed": True,
+ "provider": "notion",
+ "refresh_token": "1//MOVED",
+ "connection_id": "conn_abc",
+ "broker_user_id": "u_opaque",
+ },
+ )
+ seen = {}
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ seen["url"] = url
+ seen["headers"] = headers or {}
+ seen["json"] = json
+ return FakeResponse(200, {"access_token": "at.NEW", "expires_in": 3600})
+
+ monkeypatch.setattr(cloud.httpx, "post", fake_post)
+ profile = cloud.refresh_managed_token(secrets, config, "notion")
+ assert profile is not None and profile["access_token"] == "at.NEW"
+ assert seen["url"].endswith("/v1/oauth/notion/refresh-delegated")
+ assert "Authorization" not in seen["headers"]
+ assert seen["json"]["user_id"] == "u_opaque"
+ assert seen["json"]["connection_id"] == "conn_abc"
+
+
+def test_refresh_managed_token_undelegated_box_gives_up(secrets, config, monkeypatch):
+ """No session AND no delegation ids: nothing to present — return None
+ rather than hammering the broker."""
+ secrets.put(
+ "notion:default",
+ {"managed": True, "provider": "notion", "refresh_token": "1//X"},
+ )
+ monkeypatch.setattr(
+ cloud.httpx, "post", lambda *a, **k: (_ for _ in ()).throw(AssertionError("no call"))
+ )
+ assert cloud.refresh_managed_token(secrets, config, "notion") is None
+
+
+def test_delegate_connection_returns_opaque_user_id(secrets, config, monkeypatch):
+ secrets.put(
+ cloud.CLOUD_AUTH_PROFILE,
+ {"access_token": "sess", "expires": 9999999999},
+ )
+ seen = {}
+
+ def fake_post(url, json=None, headers=None, timeout=None):
+ seen["url"] = url
+ seen["json"] = json
+ seen["headers"] = headers or {}
+ return FakeResponse(
+ 200, {"ok": True, "user_id": "u_opaque", "machine_credential": "mc_x"}
+ )
+
+ monkeypatch.setattr(cloud.httpx, "post", fake_post)
+ # Plain delegation: no seal key sent, credential passed through if minted.
+ out = cloud.delegate_connection(secrets, config, "conn_abc")
+ assert out == {"user_id": "u_opaque", "machine_credential": "mc_x"}
+ assert seen["url"].endswith("/v1/connections/conn_abc/delegate")
+ assert seen["headers"]["Authorization"] == "Bearer sess"
+ assert seen["json"] is None # no body without a seal key
+ # With the machine's seal key: it rides the body (the broker mints there).
+ cloud.delegate_connection(secrets, config, "conn_abc", seal_pubkey="PUBKEY")
+ assert seen["json"] == {"seal_pubkey": "PUBKEY"}
+ # Hosted machine: its id rides along so the broker can wake a sandbox.
+ cloud.delegate_connection(secrets, config, "conn_abc", seal_pubkey="PUBKEY", machine_id="m1")
+ assert seen["json"] == {"seal_pubkey": "PUBKEY", "machine_id": "m1"}
diff --git a/tests/test_cloud_server.py b/tests/test_cloud_server.py
index 12f33e7d..e981f52d 100644
--- a/tests/test_cloud_server.py
+++ b/tests/test_cloud_server.py
@@ -9,10 +9,14 @@ from fastapi.testclient import TestClient
from coworker.server import SessionManager, create_app
-def _allow_managed_state(state: str = "s") -> None:
+def _allow_managed_state(state: str = "s", machine_id: str = "", machine_name: str = "") -> None:
from coworker import cloud
- cloud._pending_managed_states[state] = cloud._now()
+ cloud._pending_managed_states[state] = {
+ "created": cloud._now(),
+ "machine_id": machine_id,
+ "machine_name": machine_name,
+ }
@pytest.fixture
@@ -218,3 +222,77 @@ def test_delete_persona_refuses_builtin_and_unknown(client):
assert not body["ok"] and "built-in" in body["error"]
body = client.delete("/v1/personas/ghost").json()
assert not body["ok"] and "unknown" in body["error"]
+
+
+# -- machine-targeted connect (machines spec §Remote OAuth) -------------------
+
+
+def test_connect_managed_machine_target_open_to_all_managed(client):
+ """Connect-direct covers every managed connector now — GitHub and Slack
+ included (increment 2) — so a machine-targeted start proceeds straight
+ to the ordinary sign-in requirement."""
+ for name in ("github", "slack", "notion"):
+ body = client.post(
+ f"/v1/connectors/{name}/connect-managed",
+ json={"machine_id": "m1", "machine_name": "box"},
+ ).json()
+ assert not body["ok"]
+ assert "not signed in" in body["error"]
+
+
+def test_store_managed_grant_stages_into_ephemeral_store():
+ """The staging store produces exactly the keys a fresh connect writes —
+ account profile + default pointer for gmail, a bare default for notion —
+ and never touches disk."""
+ from coworker.connectors.setup import store_managed_grant
+ from coworker.secrets import EphemeralSecretStore
+
+ staging = EphemeralSecretStore()
+ out = store_managed_grant(
+ staging,
+ "gmail",
+ {},
+ {"type": "oauth", "managed": True, "access_token": "t", "account": "[email protected]"},
+ )
+ assert out["ok"]
+ assert set(staging.profiles()) == {"gmail:account:[email protected]", "gmail:default"}
+ assert staging.profiles()["gmail:default"]["default_account"] == "[email protected]"
+
+ # Notion rides the generic accounts layer (the live drill's
+ # notion:account:<id> finding): account profile + default pointer.
+ staging = EphemeralSecretStore()
+ out = store_managed_grant(
+ staging,
+ "notion",
+ {},
+ {"type": "oauth", "managed": True, "access_token": "t", "account": "W"},
+ )
+ assert out["ok"]
+ assert set(staging.profiles()) == {"notion:account:w", "notion:default"}
+ assert staging.profiles()["notion:default"]["default_account"] == "w"
+
+
+def test_machine_targeted_callback_stores_nothing_on_delegation_failure(
+ client, monkeypatch
+):
+ """One grant, one holder: if the delegation step fails the grant is stored
+ NOWHERE — not locally as a fallback — and the page says so."""
+ from coworker import cloud
+
+ monkeypatch.setattr(cloud, "delegate_connection", lambda *a, **k: None)
+ _allow_managed_state("t", machine_id="m1", machine_name="my-vm")
+ resp = client.post(
+ "/oauth/callback",
+ data={
+ "provider": "notion",
+ "connector": "notion",
+ "connection_id": "conn_1",
+ "access_token": "secret-token",
+ "refresh_token": "secret-refresh",
+ "account": "W",
+ "app_state": "t",
+ },
+ )
+ assert resp.status_code == 400
+ assert "nothing was stored" in resp.text.lower()
+ assert client.manager.secrets.get("notion:default") is None
diff --git a/tests/test_remote_home.py b/tests/test_remote_home.py
new file mode 100644
index 00000000..6e329fa7
--- /dev/null
+++ b/tests/test_remote_home.py
@@ -0,0 +1,2489 @@
+"""Remote homes P1a: identity, channel, and the full loopback join.
+
+The loopback tests run the REAL stack end-to-end in one process: a controller
+app served by uvicorn on an ephemeral port, and a joined box (its own
+SessionManager + app over a separate state dir) dialing it over a real
+WebSocket — enrollment, challenge-response, clone trap, token expiry, and the
+proxy round trip all cross an actual socket.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from coworker.remote import channel as ch
+from coworker.remote.identity import load_or_create, verify_b64
+from coworker.remote.joiner import (
+ JoinRejected,
+ load_remote_config,
+ parse_join_url,
+ run_joined,
+)
+from coworker.remote.registry import MachinesRegistry
+from coworker.server.app import create_app
+from coworker.server.manager import SessionManager
+
+
+# -- identity ------------------------------------------------------------------
+
+
+def test_identity_created_once_and_private(tmp_path):
+ first = load_or_create(tmp_path)
+ again = load_or_create(tmp_path)
+ assert first.public_key_b64 == again.public_key_b64
+ assert (tmp_path / "machine.key").stat().st_mode & 0o777 == 0o600
+ assert len(first.fingerprint) == 16
+
+
+def test_sealing_round_trip_and_tamper(tmp_path):
+ from coworker.remote.identity import seal_b64
+
+ box = load_or_create(tmp_path / "box")
+ other = load_or_create(tmp_path / "other")
+ blob = seal_b64(box.seal_public_key_b64, b'{"profiles": {"openai": {}}}')
+ assert box.unseal_b64(blob) == b'{"profiles": {"openai": {}}}'
+ # Only the sealed-to machine can open it.
+ with pytest.raises(ValueError):
+ other.unseal_b64(blob)
+ # A flipped byte fails authentication, never yields garbage plaintext.
+ import base64
+
+ raw = bytearray(base64.b64decode(blob))
+ raw[-1] ^= 0x01
+ with pytest.raises(ValueError):
+ box.unseal_b64(base64.b64encode(bytes(raw)).decode())
+ assert (tmp_path / "box" / "machine.seal.key").stat().st_mode & 0o777 == 0o600
+
+
+def test_pre_sealing_state_dir_grows_seal_key(tmp_path):
+ # A box created before the sealing key gains one in place, keeping its
+ # signing identity (the pre-release backfill path).
+ first = load_or_create(tmp_path)
+ (tmp_path / "machine.seal.key").unlink()
+ again = load_or_create(tmp_path)
+ assert again.public_key_b64 == first.public_key_b64
+ assert again.seal_public_key_b64 # regenerated
+
+
+def test_signature_verifies_and_tamper_fails(tmp_path):
+ identity = load_or_create(tmp_path)
+ signature = identity.sign_b64(b"nonce-bytes")
+ assert verify_b64(identity.public_key_b64, b"nonce-bytes", signature)
+ assert not verify_b64(identity.public_key_b64, b"other-bytes", signature)
+ other = load_or_create(tmp_path / "other")
+ assert not verify_b64(other.public_key_b64, b"nonce-bytes", signature)
+
+
+def test_seal_attestation_verifies_and_rejects_substitution(tmp_path):
+ from coworker.remote.identity import verify_seal_attestation
+
+ box = load_or_create(tmp_path / "box")
+ sig = box.attest_seal_key_b64()
+ assert verify_seal_attestation(box.public_key_b64, box.seal_public_key_b64, sig)
+ # A substituted sealing key (the middlebox move) fails against the box's sig.
+ mitm = load_or_create(tmp_path / "mitm")
+ assert not verify_seal_attestation(box.public_key_b64, mitm.seal_public_key_b64, sig)
+ # ...and the middlebox's own attestation never verifies under the box's key.
+ assert not verify_seal_attestation(
+ box.public_key_b64, mitm.seal_public_key_b64, mitm.attest_seal_key_b64()
+ )
+ # Domain separation: a plain signature over the raw key bytes is not an
+ # attestation — the identity key must have signed the tagged message.
+ import base64
+
+ plain = box.sign_b64(base64.b64decode(box.seal_public_key_b64))
+ assert not verify_seal_attestation(box.public_key_b64, box.seal_public_key_b64, plain)
+ assert not verify_seal_attestation(box.public_key_b64, "not-base64!!", sig)
+
+
+# -- join URL ------------------------------------------------------------------
+
+
+def test_parse_join_url():
+ base, token = parse_join_url("http://127.0.0.1:9787/j/abc123")
+ assert base == "http://127.0.0.1:9787"
+ assert token == "abc123"
+ with pytest.raises(ValueError):
+ parse_join_url("http://127.0.0.1:9787/nope/abc123")
+ with pytest.raises(ValueError):
+ parse_join_url("ssh://host/j/tok")
+
+
+def test_in_memory_ephemera_semantics():
+ import time as _time
+
+ from coworker.remote.stores import InMemoryEphemera
+
+ eph = InMemoryEphemera()
+ eph.add_token("t1", _time.time() + 60)
+ assert eph.has_tokens()
+ assert eph.consume_token("t1") == {"fingerprint": "", "org_id": "", "actor": "", "provenance": {}}
+ assert eph.consume_token("t1") is None # single-use
+ eph.add_token("t2", _time.time() - 1)
+ assert eph.consume_token("t2") is None # expired
+ assert not eph.has_tokens()
+ eph.add_token("t3", _time.time() + 60, bound_fingerprint="fp42", org_id="org-a", actor="erin")
+ assert eph.consume_token("t3") == {"fingerprint": "fp42", "org_id": "org-a", "actor": "erin", "provenance": {}}
+ # A managed sandbox's token names the sandbox it was minted for.
+ eph.add_token("t4", _time.time() + 60, provenance={"kind": "fly", "ref": "sb1"})
+ assert eph.consume_token("t4")["provenance"] == {"kind": "fly", "ref": "sb1"}
+ assert eph.acquire_lease("pk")
+ assert not eph.acquire_lease("pk") # clone trap
+ eph.release_lease("pk")
+ assert eph.acquire_lease("pk")
+
+
+# -- registry ------------------------------------------------------------------
+
+
+def test_registry_name_collision_suffixes(tmp_path):
+ reg = MachinesRegistry(tmp_path / "coworker.db")
+ a = reg.enroll("dev-box", "pk-a")
+ b = reg.enroll("dev-box", "pk-b")
+ assert a["name"] == "dev-box"
+ assert b["name"] == "dev-box-2"
+ with pytest.raises(ValueError):
+ reg.enroll("whatever", "pk-a") # pubkey already enrolled
+ with pytest.raises(ValueError):
+ reg.rename(b["id"], "dev-box") # rename into a taken name
+
+
+def test_registry_names_unique_per_org(tmp_path):
+ reg = MachinesRegistry(tmp_path / "orgdb")
+ a = reg.enroll("box", "pk-1", org_id="org-a")
+ b = reg.enroll("box", "pk-2", org_id="org-b")
+ c = reg.enroll("box", "pk-3", org_id="org-a")
+ assert a["name"] == "box" and b["name"] == "box" # same name, different orgs
+ assert c["name"] == "box-2" # suffix within the org only
+ assert [m["id"] for m in reg.list("org-a")] == [a["id"], c["id"]]
+ assert [m["id"] for m in reg.list("org-b")] == [b["id"]]
+ assert len(reg.list()) == 3 # None = unscoped (admin/desktop)
+
+
+# -- loopback harness ----------------------------------------------------------
+
+
+class _Server:
+ """The real controller app under real uvicorn on an ephemeral port."""
+
+ def __init__(self, app):
+ import uvicorn
+
+ self._config = uvicorn.Config(
+ app, host="127.0.0.1", port=0, log_level="error", ws_max_size=16 * 2**20
+ )
+ self._server = uvicorn.Server(self._config)
+ self._task = None
+
+ async def __aenter__(self):
+ self._task = asyncio.create_task(self._server.serve())
+ while not self._server.started:
+ await asyncio.sleep(0.01)
+ port = self._server.servers[0].sockets[0].getsockname()[1]
+ self.base = f"http://127.0.0.1:{port}"
+ return self
+
+ async def __aexit__(self, *exc):
+ self._server.should_exit = True
+ await self._task
+
+
+def _controller(tmp_path: Path):
+ manager = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ return create_app(manager)
+
+
+def _box_app(tmp_path: Path, name: str = "box"):
+ manager = SessionManager(data_dir=tmp_path / name)
+ return create_app(manager)
+
+
+async def _arm(base: str) -> str:
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(f"{base}/v1/remote/arm")
+ resp.raise_for_status()
+ return resp.json()["join_url"]
+
+
+async def _join_box(tmp_path, base, name="box", state_name=None, once=True):
+ """Run one join (enroll + serve) in a background task; return the task."""
+ join_url = await _arm(base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / (state_name or f"{name}-state")
+ state.mkdir(parents=True, exist_ok=True)
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=base,
+ name=name,
+ token=token,
+ app=_box_app(tmp_path, f"{name}-data"),
+ once=once,
+ log=lambda *_: None,
+ )
+ )
+ return task, state
+
+
+async def _wait_connected(base: str, expect: int = 1, timeout: float = 5.0):
+ async with httpx.AsyncClient() as client:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while True:
+ resp = await client.get(f"{base}/v1/machines")
+ machines = [m for m in resp.json()["machines"] if m["connected"]]
+ if len(machines) >= expect:
+ return resp.json()["machines"]
+ if asyncio.get_running_loop().time() > deadline:
+ raise AssertionError(
+ f"expected {expect} connected machine(s), have {machines}"
+ )
+ await asyncio.sleep(0.05)
+
+
+# -- loopback tests ------------------------------------------------------------
+
+
+async def test_join_enrolls_and_proxies(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, state = await _join_box(tmp_path, server.base)
+ try:
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ assert machines[0]["name"] == "box"
+ assert machines[0]["connected"] is True
+
+ # THE P1a proof: the box's own /v1 surface, through the controller.
+ async with httpx.AsyncClient() as client:
+ health = await client.get(
+ f"{server.base}/v1/machines/{mid}/p/v1/health"
+ )
+ assert health.status_code == 200
+ sessions = await client.get(
+ f"{server.base}/v1/machines/{mid}/p/v1/sessions"
+ )
+ assert sessions.status_code == 200
+ assert isinstance(sessions.json().get("sessions"), list)
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_token_is_single_use_and_unknown_pubkey_rejected(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state_a = tmp_path / "a-state"
+ state_a.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state_a,
+ controller=server.base,
+ name="a",
+ token=token,
+ app=_box_app(tmp_path, "a-data"),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ await _wait_connected(server.base)
+ # Same token, DIFFERENT identity: single-use means rejection.
+ state_b = tmp_path / "b-state"
+ state_b.mkdir()
+ with pytest.raises(JoinRejected) as err:
+ await run_joined(
+ state=state_b,
+ controller=server.base,
+ name="b",
+ token=token,
+ app=_box_app(tmp_path, "b-data"),
+ once=True,
+ log=lambda *_: None,
+ )
+ assert err.value.reason == "not-enrolled"
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_clone_trap_refuses_second_connection(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, state = await _join_box(tmp_path, server.base)
+ try:
+ await _wait_connected(server.base)
+ # Same state dir (same private key) dialing again = a clone.
+ with pytest.raises(JoinRejected) as err:
+ await run_joined(
+ state=state,
+ controller=server.base,
+ name="box",
+ app=_box_app(tmp_path, "clone-data"),
+ once=True,
+ log=lambda *_: None,
+ )
+ assert err.value.reason == "already-connected"
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_reconnect_without_token_uses_challenge(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, state = await _join_box(tmp_path, server.base)
+ try:
+ await _wait_connected(server.base)
+ assert load_remote_config(state) is None or True # config written by CLI join only
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ # Box comes back with NO token — identity alone must be enough (`up`).
+ task2 = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="box",
+ app=_box_app(tmp_path, "box-data2"),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ assert machines[0]["name"] == "box" # same machine row, not a new enrollment
+ assert len(machines) == 1
+ finally:
+ task2.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task2
+
+
+async def test_protocol_mismatch_rejected(tmp_path):
+ # Speak the wire directly: patching the shared PROTOCOL_VERSION constant
+ # would change BOTH sides in one process and they'd happily agree.
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ identity = load_or_create(tmp_path / "old-state")
+ ws_url = server.base.replace("http://", "ws://") + "/ws/machine"
+ async with websockets.connect(ws_url) as ws:
+ await ws.send(
+ json.dumps(
+ {
+ "type": "hello",
+ "protocol_version": ch.PROTOCOL_VERSION - 1,
+ "app_version": "0.0.0",
+ "pubkey": identity.public_key_b64,
+ "name": "old",
+ "token": token,
+ }
+ )
+ )
+ frame = json.loads(await ws.recv())
+ assert frame["type"] == "reject"
+ assert frame["reason"] == "protocol-mismatch"
+ assert "update" in frame["detail"]
+
+
+async def _wire_join(ws, identity, token=None, seal_pubkey=None, seal_sig=None, name="box"):
+ """Speak the machine handshake by hand; return the post-auth frame."""
+ hello = {
+ "type": "hello",
+ "protocol_version": ch.PROTOCOL_VERSION,
+ "app_version": "0.0.0",
+ "pubkey": identity.public_key_b64,
+ "name": name,
+ }
+ if token:
+ hello["token"] = token
+ if seal_pubkey is not None:
+ hello["seal_pubkey"] = seal_pubkey
+ if seal_sig is not None:
+ hello["seal_sig"] = seal_sig
+ await ws.send(json.dumps(hello))
+ frame = json.loads(await ws.recv())
+ if frame["type"] != "challenge":
+ return frame
+ signature = identity.sign_b64(ch.decode_body(frame["nonce"]))
+ await ws.send(json.dumps({"type": "auth", "signature": signature}))
+ return json.loads(await ws.recv())
+
+
+async def test_unattested_seal_key_rejected_at_enroll(tmp_path):
+ # A middlebox that swaps its own sealing key into the hello passes the
+ # challenge (that only proves the identity key) but must not get its key
+ # pinned — the acceptor requires the seal key signed by that identity.
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ _, token = parse_join_url(await _arm(server.base))
+ box = load_or_create(tmp_path / "box-state")
+ mitm = load_or_create(tmp_path / "mitm-state")
+ ws_url = server.base.replace("http://", "ws://") + "/ws/machine"
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(
+ ws,
+ box,
+ token=token,
+ seal_pubkey=mitm.seal_public_key_b64, # swapped in transit
+ seal_sig=box.attest_seal_key_b64(), # signs the REAL key
+ )
+ assert frame["type"] == "reject"
+ assert frame["reason"] == "bad-seal-attestation"
+ async with httpx.AsyncClient() as client:
+ resp = await client.get(f"{server.base}/v1/machines")
+ assert resp.json()["machines"] == [] # nothing was enrolled
+
+
+async def _device_approve_cycle(client, base: str, fingerprint: str, name: str = "vm"):
+ """Run start → approve → poll; return (user_code, join token)."""
+ start = (
+ await client.post(
+ f"{base}/v1/remote/device/start",
+ json={"name": name, "fingerprint": fingerprint},
+ )
+ ).json()
+ resp = await client.post(f"{base}/v1/remote/device/{start['user_code']}/approve")
+ assert resp.status_code == 200
+ poll = (
+ await client.post(
+ f"{base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ assert poll["status"] == "approved"
+ _, token = parse_join_url(poll["join_url"])
+ return start, token
+
+
+async def test_device_flow_mints_identity_bound_token(tmp_path):
+ # `openworker auth join`: the box asks, the user approves a NAMED identity,
+ # approval mints the one join token — bound so only that identity can use it.
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ box = load_or_create(tmp_path / "box-state")
+ rogue = load_or_create(tmp_path / "rogue-state")
+ ws_url = server.base.replace("http://", "ws://") + "/ws/machine"
+ async with httpx.AsyncClient() as client:
+ start = (
+ await client.post(
+ f"{server.base}/v1/remote/device/start",
+ json={"name": "vm", "fingerprint": box.fingerprint},
+ )
+ ).json()
+ assert start["user_code"] and start["device_code"]
+ poll = (
+ await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ assert poll["status"] == "pending"
+ # The approval surface shows what the user must verify.
+ listed = (await client.get(f"{server.base}/v1/remote/device")).json()
+ assert listed["requests"][0]["name"] == "vm"
+ assert listed["requests"][0]["fingerprint"] == box.fingerprint
+ resp = await client.post(
+ f"{server.base}/v1/remote/device/{start['user_code']}/approve"
+ )
+ assert resp.status_code == 200
+ poll = (
+ await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ assert poll["status"] == "approved"
+ _, token = parse_join_url(poll["join_url"])
+ # Single-shot delivery: the grant is gone after handing out the URL.
+ poll2 = (
+ await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ assert poll2["status"] == "expired"
+
+ # A different identity presenting the approved token is refused
+ # (and the token burns — single-use).
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(
+ ws,
+ rogue,
+ token=token,
+ seal_pubkey=rogue.seal_public_key_b64,
+ seal_sig=rogue.attest_seal_key_b64(),
+ )
+ assert frame["type"] == "reject"
+ assert frame["reason"] == "wrong-machine"
+
+ # A fresh approval lets the approved box itself in.
+ _, token2 = await _device_approve_cycle(client, server.base, box.fingerprint)
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(
+ ws,
+ box,
+ token=token2,
+ seal_pubkey=box.seal_public_key_b64,
+ seal_sig=box.attest_seal_key_b64(),
+ )
+ assert frame["type"] == "welcome"
+
+
+async def test_device_flow_deny(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ async with httpx.AsyncClient() as client:
+ start = (
+ await client.post(
+ f"{server.base}/v1/remote/device/start",
+ json={"name": "vm", "fingerprint": "fp"},
+ )
+ ).json()
+ resp = await client.post(
+ f"{server.base}/v1/remote/device/{start['user_code']}/deny"
+ )
+ assert resp.status_code == 200
+ poll = (
+ await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ assert poll["status"] == "denied"
+ # Denied grants can't be resurrected by a late approve.
+ resp = await client.post(
+ f"{server.base}/v1/remote/device/{start['user_code']}/approve"
+ )
+ assert resp.status_code == 404
+
+
+async def test_auth_join_cli_runs_device_flow(tmp_path, monkeypatch):
+ # The CLI half: prints a code, polls, then hands off to the ordinary token
+ # join once approved (the enrollment primitive never varies).
+ import coworker.remote.joiner as joiner_mod
+
+ async with _Server(_controller(tmp_path)) as server:
+ captured = {}
+ monkeypatch.setattr(
+ joiner_mod,
+ "_cmd_join",
+ lambda state, url, name: captured.update(url=url, name=name) or 0,
+ )
+
+ async def approve():
+ async with httpx.AsyncClient() as client:
+ for _ in range(200):
+ listed = (await client.get(f"{server.base}/v1/remote/device")).json()
+ if listed["requests"]:
+ req = listed["requests"][0]
+ resp = await client.post(
+ f"{server.base}/v1/remote/device/{req['user_code']}/approve"
+ )
+ assert resp.status_code == 200
+ return req
+ await asyncio.sleep(0.02)
+ raise AssertionError("no device request appeared")
+
+ approve_task = asyncio.create_task(approve())
+ state = tmp_path / "auth-box-state"
+ rc = await asyncio.to_thread(
+ joiner_mod._cmd_auth_join, state, server.base, "authbox", 0.05
+ )
+ req = await approve_task
+ assert rc == 0
+ assert req["name"] == "authbox"
+ assert req["fingerprint"] == load_or_create(state).fingerprint
+ assert captured["url"].startswith(server.base + "/j/")
+ assert captured["name"] == "authbox"
+
+
+async def test_seal_key_backfill_requires_attestation(tmp_path):
+ # A box enrolled before it had a sealing key pins one on reconnect — but
+ # only an attested one; a bare seal_pubkey in the hello is refused.
+ import websockets
+
+ manager = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ async with _Server(create_app(manager)) as server:
+ _, token = parse_join_url(await _arm(server.base))
+ box = load_or_create(tmp_path / "box-state")
+ ws_url = server.base.replace("http://", "ws://") + "/ws/machine"
+ # Enroll with no sealing key at all (a pre-wallet box).
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(ws, box, token=token)
+ assert frame["type"] == "welcome"
+ # Reconnect offering an unattested seal key: refused, not pinned.
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(ws, box, seal_pubkey=box.seal_public_key_b64)
+ assert frame["type"] == "reject"
+ assert frame["reason"] == "bad-seal-attestation"
+ reg = MachinesRegistry(manager.session_store.db_path)
+ assert reg.by_pubkey(box.public_key_b64)["seal_pubkey"] == ""
+ # Reconnect with the attestation: backfilled.
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(
+ ws,
+ box,
+ seal_pubkey=box.seal_public_key_b64,
+ seal_sig=box.attest_seal_key_b64(),
+ )
+ assert frame["type"] == "welcome"
+ assert (
+ reg.by_pubkey(box.public_key_b64)["seal_pubkey"]
+ == box.seal_public_key_b64
+ )
+
+
+async def test_offline_machine_returns_503_and_unknown_404(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, _ = await _join_box(tmp_path, server.base)
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ async with httpx.AsyncClient() as client:
+ # Wait for the acceptor to notice the disconnect.
+ deadline = asyncio.get_running_loop().time() + 5
+ while True:
+ listing = await client.get(f"{server.base}/v1/machines")
+ if not any(m["connected"] for m in listing.json()["machines"]):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+ offline = await client.get(f"{server.base}/v1/machines/{mid}/p/v1/health")
+ assert offline.status_code == 503
+ unknown = await client.get(
+ f"{server.base}/v1/machines/nosuch/p/v1/health"
+ )
+ assert unknown.status_code == 404
+ # Offline machines still LIST (greyed in the GUI, never vanished).
+ listing = await client.get(f"{server.base}/v1/machines")
+ row = listing.json()["machines"][0]
+ assert row["id"] == mid and row["connected"] is False
+
+
+async def test_remove_connected_machine_refused_offline_allowed(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, _ = await _join_box(tmp_path, server.base)
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ async with httpx.AsyncClient() as client:
+ refused = await client.delete(f"{server.base}/v1/machines/{mid}")
+ assert refused.status_code == 409
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ deadline = asyncio.get_running_loop().time() + 5
+ while True:
+ listing = await client.get(f"{server.base}/v1/machines")
+ if not any(m["connected"] for m in listing.json()["machines"]):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+ removed = await client.delete(f"{server.base}/v1/machines/{mid}")
+ assert removed.status_code == 200
+ listing = await client.get(f"{server.base}/v1/machines")
+ assert listing.json()["machines"] == []
+
+
+async def test_rename_machine(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ task, _ = await _join_box(tmp_path, server.base)
+ try:
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ async with httpx.AsyncClient() as client:
+ resp = await client.patch(
+ f"{server.base}/v1/machines/{mid}", json={"name": "gpu-rig"}
+ )
+ assert resp.status_code == 200
+ listing = await client.get(f"{server.base}/v1/machines")
+ assert listing.json()["machines"][0]["name"] == "gpu-rig"
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_join_hint_page_is_tokenless_and_constant(tmp_path):
+ async with _Server(_controller(tmp_path)) as server:
+ async with httpx.AsyncClient() as client:
+ real = await _arm(server.base)
+ _, token = parse_join_url(real)
+ valid = await client.get(f"{server.base}/j/{token}")
+ bogus = await client.get(f"{server.base}/j/definitely-not-a-token")
+ assert valid.status_code == bogus.status_code == 200
+ assert valid.text == bogus.text # must not confirm token validity
+ # …and looking at the hint page must NOT consume the token: a real
+ # join with it still works.
+ state = tmp_path / "hint-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="hint",
+ token=token,
+ app=_box_app(tmp_path, "hint-data"),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ await _wait_connected(server.base)
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_offline_machine_serves_session_snapshot(tmp_path):
+ """The vanish bug (owner-hit 2026-08-25): an offline machine's sessions must
+ come from the controller's stored snapshot — greyed, never vanished."""
+ from coworker.sessions import SessionRecord
+
+ async with _Server(_controller(tmp_path)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "snap-state"
+ state.mkdir()
+ box_manager = SessionManager(data_dir=tmp_path / "snap-data")
+ box_manager.session_store.save(
+ SessionRecord(
+ session_id="snap-1",
+ workspace="",
+ model="m",
+ mode="interactive",
+ title="Nightly watch",
+ messages=[
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello from the box"},
+ ],
+ )
+ )
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="snap-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ async with httpx.AsyncClient() as client:
+ live = await client.get(f"{server.base}/v1/machines/{mid}/sessions")
+ assert live.json()["live"] is True
+ assert [s["session_id"] for s in live.json()["sessions"]] == ["snap-1"]
+ # Cache-on-view: fetch the transcript while connected — that's what
+ # makes it readable later.
+ viewed = await client.get(
+ f"{server.base}/v1/machines/{mid}/sessions/snap-1/messages"
+ )
+ assert viewed.json()["live"] is True
+ assert len(viewed.json()["messages"]) == 2
+
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ deadline = asyncio.get_running_loop().time() + 5
+ while True:
+ listing = await client.get(f"{server.base}/v1/machines")
+ if not any(m["connected"] for m in listing.json()["machines"]):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+
+ cached = await client.get(f"{server.base}/v1/machines/{mid}/sessions")
+ assert cached.json()["live"] is False
+ rows = cached.json()["sessions"]
+ assert [s["session_id"] for s in rows] == ["snap-1"]
+ assert rows[0]["title"] == "Nightly watch"
+ # The viewed transcript is still readable offline (read-only)…
+ replay = await client.get(
+ f"{server.base}/v1/machines/{mid}/sessions/snap-1/messages"
+ )
+ assert replay.json() == {
+ "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "hello from the box"},
+ ],
+ "live": False,
+ "cached": True,
+ }
+ # …while a NEVER-viewed transcript honestly has no copy.
+ unseen = await client.get(
+ f"{server.base}/v1/machines/{mid}/sessions/never-opened/messages"
+ )
+ assert unseen.json()["cached"] is False
+ # Unknown machines still 404 (no phantom snapshots).
+ missing = await client.get(f"{server.base}/v1/machines/nosuch/sessions")
+ assert missing.status_code == 404
+
+
+def test_js_sealed_blob_unseals():
+ """Cross-language pin (OPE-149): this blob was produced by the SPA's
+ seal.ts (noble x25519 + hkdf-sha256 + chacha20-poly1305) against the
+ fixture key. The box-side unseal must open it forever — a drift in either
+ implementation fails here, not in a user's browser."""
+ import base64
+
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
+
+ from coworker.remote.identity import MachineIdentity
+
+ fixture_priv = "UGaZYTzlePyN5LU5/VIOJbBPYUbU6n7wq6b/VMWd/UU="
+ fixture_blob = (
+ "JOTCfuu/MZ5dGUONsHCk0DrVR8zZdj3riSfIQZSyjmJHp6b2Mo0VmYo6AP8zo7mi"
+ "sg5/DzJMA0u4ZKNBgEMLM6foGT/tgmkCprqm4eX/QUG+dPB7h2XySU0fQBqjLlE7"
+ "mot28tvt07KJM/8+vQ=="
+ )
+ ident = MachineIdentity(
+ Ed25519PrivateKey.generate(),
+ X25519PrivateKey.from_private_bytes(base64.b64decode(fixture_priv)),
+ )
+ assert json.loads(ident.unseal_b64(fixture_blob)) == {
+ "profiles": {"provider:anthropic": {"api_key": "sk-test-123"}}
+ }
+
+
+async def test_browser_sealed_deploy_relay(tmp_path):
+ """OPE-149: a client that sealed to the machine's pinned key itself can
+ deploy through the acceptor as a blind relay — no wallet consulted, the
+ plaintext never touches the controller, the ledger records the client's
+ hash and the audit event says the source was browser-sealed."""
+ from coworker.remote.identity import seal_b64
+
+ ctrl_manager = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ async with _Server(create_app(ctrl_manager)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "sealed-state"
+ state.mkdir()
+ box_manager = SessionManager(data_dir=tmp_path / "sealed-data")
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="sealed-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ row = machines[0]
+ # The list exposes the sealing key's public half + fingerprint —
+ # what a browser seals to and what the user verifies.
+ assert row["seal_pubkey"]
+ assert len(row["seal_fingerprint"]) == 16
+ sealed = seal_b64(
+ row["seal_pubkey"],
+ json.dumps(
+ {"profiles": {"provider:anthropic": {"api_key": "sk-sealed-1"}}}
+ ).encode(),
+ )
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ f"{server.base}/v1/machines/{row['id']}/secrets",
+ json={
+ "sealed_b64": sealed,
+ "profiles": ["provider:anthropic"],
+ "hashes": {"provider:anthropic": "h" * 64},
+ },
+ )
+ assert resp.status_code == 200
+ assert resp.json()["deployed"] == ["provider:anthropic"]
+ assert box_manager.secrets.get("provider:anthropic") == {
+ "api_key": "sk-sealed-1"
+ }
+ ledger = (
+ await client.get(
+ f"{server.base}/v1/machines/{row['id']}/secrets"
+ )
+ ).json()["secrets"]
+ assert [r["profile"] for r in ledger] == ["provider:anthropic"]
+ audit_path = (
+ ctrl_manager.session_store.db_path.parent / "remote-audit.jsonl"
+ )
+ events = [
+ json.loads(line) for line in audit_path.read_text().splitlines()
+ ]
+ deploy = next(
+ e for e in events if e["entity"]["type"] == "secret_deploy"
+ )
+ assert deploy["unmapped"]["source"] == "browser-sealed"
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_wallet_deploy_revoke_and_staleness(tmp_path):
+ """Keys wallet end-to-end over loopback: sealed deploy lands in the BOX's
+ SecretStore, the ledger tracks it, rotation shows as stale, revoke scrubs."""
+ ctrl_manager = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ ctrl_manager.secrets.put("openai", {"api_key": "sk-first"})
+ ctrl_manager.secrets.put("tavily", {"api_key": "tv-1"})
+ async with _Server(create_app(ctrl_manager)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "w-state"
+ state.mkdir()
+ box_manager = SessionManager(data_dir=tmp_path / "w-data")
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="wallet-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ async with httpx.AsyncClient() as client:
+ # Deploy two profiles; the box's own store receives copies.
+ resp = await client.post(
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["openai", "tavily"]},
+ )
+ assert resp.status_code == 200
+ assert resp.json()["deployed"] == ["openai", "tavily"]
+ assert box_manager.secrets.get("openai") == {"api_key": "sk-first"}
+ assert box_manager.secrets.get("tavily") == {"api_key": "tv-1"}
+
+ ledger = (
+ await client.get(f"{server.base}/v1/machines/{mid}/secrets")
+ ).json()["secrets"]
+ assert {r["profile"] for r in ledger} == {"openai", "tavily"}
+ assert not any(r["stale"] for r in ledger)
+
+ # Rotate = update the wallet, deploy again (owner ruling: no
+ # third verb). In between, the ledger shows stale.
+ ctrl_manager.secrets.put("openai", {"api_key": "sk-rotated"})
+ ledger = (
+ await client.get(f"{server.base}/v1/machines/{mid}/secrets")
+ ).json()["secrets"]
+ assert next(r for r in ledger if r["profile"] == "openai")["stale"]
+ resp = await client.post(
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["openai"]},
+ )
+ assert resp.status_code == 200
+ assert box_manager.secrets.get("openai") == {"api_key": "sk-rotated"}
+ ledger = (
+ await client.get(f"{server.base}/v1/machines/{mid}/secrets")
+ ).json()["secrets"]
+ assert not any(r["stale"] for r in ledger)
+
+ # Revoke scrubs the box and the ledger (DELETE with a body).
+ resp = await client.request(
+ "DELETE",
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["tavily"]},
+ )
+ assert resp.status_code == 200
+ assert box_manager.secrets.get("tavily") is None
+ assert box_manager.secrets.get("openai") is not None
+ ledger = (
+ await client.get(f"{server.base}/v1/machines/{mid}/secrets")
+ ).json()["secrets"]
+ assert {r["profile"] for r in ledger} == {"openai"}
+
+ # Unknown wallet profile → clear 400, nothing deployed.
+ resp = await client.post(
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["nope"]},
+ )
+ assert resp.status_code == 400
+
+ # The audit trail saw it all: enroll, three deploys, one revoke —
+ # OCSF Entity Management events, profile names only, never values.
+ audit_path = (
+ ctrl_manager.session_store.db_path.parent / "remote-audit.jsonl"
+ )
+ events = [
+ json.loads(line) for line in audit_path.read_text().splitlines()
+ ]
+ assert all(e["class_uid"] == 3004 for e in events)
+ assert [
+ (e["activity_name"], e["entity"]["type"], e["entity"]["name"])
+ for e in events
+ ] == [
+ ("create", "machine", "wallet-box"),
+ ("create", "secret_deploy", "openai"),
+ ("create", "secret_deploy", "tavily"),
+ ("create", "secret_deploy", "openai"), # the rotation redeploy
+ ("delete", "secret_deploy", "tavily"),
+ ]
+ raw = audit_path.read_text()
+ assert "sk-first" not in raw and "sk-rotated" not in raw
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_wallet_deploy_requires_live_machine(tmp_path):
+ ctrl_manager = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ ctrl_manager.secrets.put("openai", {"api_key": "sk-x"})
+ async with _Server(create_app(ctrl_manager)) as server:
+ task, _ = await _join_box(tmp_path, server.base)
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ async with httpx.AsyncClient() as client:
+ deadline = asyncio.get_running_loop().time() + 5
+ while True:
+ listing = await client.get(f"{server.base}/v1/machines")
+ if not any(m["connected"] for m in listing.json()["machines"]):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+ resp = await client.post(
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["openai"]},
+ )
+ assert resp.status_code == 503
+
+
+def test_secrets_cli_set_and_list(tmp_path, capsys, monkeypatch):
+ from coworker.remote import joiner
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "s-state"))
+ assert joiner.cli(["secrets", "set", "openai", "api_key=sk-local"]) == 0
+ assert "stored profile 'openai'" in capsys.readouterr().out
+ assert joiner.cli(["secrets", "list"]) == 0
+ assert "openai" in capsys.readouterr().out
+ from coworker.secrets import SecretStore
+
+ store = SecretStore(tmp_path / "s-state" / "secrets.json")
+ assert store.get("openai") == {"api_key": "sk-local"}
+ assert joiner.cli(["secrets", "set", "bad", "no-equals"]) == 2
+
+
+# -- bridged session WebSocket (P1c) -------------------------------------------
+
+
+def _scripted_provider(turns):
+ from coworker.providers import ModelCapabilities, ProviderClient
+
+ class _Scripted(ProviderClient):
+ def __init__(self):
+ self._turns = list(turns)
+
+ def complete(self, *, model, messages, tools=None, **settings):
+ # Auto-title and other side-turns share this provider: keep
+ # replaying the last turn instead of running dry.
+ return self._turns.pop(0) if len(self._turns) > 1 else self._turns[0]
+
+ def capabilities(self, model):
+ return ModelCapabilities()
+
+ return _Scripted()
+
+
+def _scripted_box_app(tmp_path, name, texts):
+ from coworker.providers import AssistantTurn
+
+ workspace = tmp_path / f"{name}-ws"
+ workspace.mkdir(exist_ok=True)
+ manager = SessionManager(
+ workspace=workspace,
+ data_dir=tmp_path / name,
+ provider=_scripted_provider(
+ [AssistantTurn(text=t, finish_reason="stop") for t in texts]
+ ),
+ )
+ return create_app(manager)
+
+
+async def test_bridged_session_ws_runs_a_turn_on_the_box(tmp_path):
+ """The P1c proof: a chat turn executes on the BOX's engine, streamed live to
+ a client connected to the CONTROLLER's bridged socket."""
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "chat-state"
+ state.mkdir()
+ box = _scripted_box_app(tmp_path, "chat-data", ["Hello from the box."])
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="chat-box",
+ token=token,
+ app=box,
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ bridge_url = (
+ server.base.replace("http://", "ws://")
+ + f"/ws/machines/{mid}/p/ws/session/remote-chat-1"
+ )
+ async with websockets.connect(bridge_url) as ws:
+ first = json.loads(await ws.recv())
+ assert first["type"] == "ready"
+ await ws.send(json.dumps({"type": "user_message", "text": "hi"}))
+ texts, done = [], False
+ while not done:
+ event = json.loads(await asyncio.wait_for(ws.recv(), timeout=10))
+ if event["type"] == "assistant_message":
+ texts.append(event["data"]["text"])
+ done = event["type"] == "turn_done"
+ assert texts == ["Hello from the box."]
+
+ # And the session persisted on the BOX, visible through the proxy —
+ # the desktop persisted nothing of it.
+ async with httpx.AsyncClient() as client:
+ remote = await client.get(
+ f"{server.base}/v1/machines/{mid}/p/v1/sessions"
+ )
+ ids = [s["session_id"] for s in remote.json()["sessions"]]
+ assert "remote-chat-1" in ids
+ local = await client.get(f"{server.base}/v1/sessions")
+ assert "remote-chat-1" not in [
+ s["session_id"] for s in local.json()["sessions"]
+ ]
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_bridged_ws_to_offline_machine_closes_immediately(tmp_path):
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ task, _ = await _join_box(tmp_path, server.base)
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ deadline = asyncio.get_running_loop().time() + 5
+ async with httpx.AsyncClient() as client:
+ while True:
+ listing = await client.get(f"{server.base}/v1/machines")
+ if not any(m["connected"] for m in listing.json()["machines"]):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+ bridge_url = (
+ server.base.replace("http://", "ws://")
+ + f"/ws/machines/{mid}/p/ws/session/x"
+ )
+ # Close-before-accept surfaces as a rejected handshake — the client
+ # fails fast instead of hanging on a socket to nowhere.
+ with pytest.raises(websockets.InvalidStatus):
+ async with websockets.connect(bridge_url):
+ pass
+
+
+async def test_box_death_closes_bridged_sockets(tmp_path):
+ import websockets
+
+ async with _Server(_controller(tmp_path)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "drop-state"
+ state.mkdir()
+ box = _scripted_box_app(tmp_path, "drop-data", ["never sent"])
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="drop-box",
+ token=token,
+ app=box,
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ bridge_url = (
+ server.base.replace("http://", "ws://")
+ + f"/ws/machines/{mid}/p/ws/session/drop-1"
+ )
+ async with websockets.connect(bridge_url) as ws:
+ first = json.loads(await ws.recv())
+ assert first["type"] == "ready"
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ # The GUI-facing socket must die with the machine, not hang.
+ with pytest.raises(websockets.ConnectionClosed):
+ while True:
+ await asyncio.wait_for(ws.recv(), timeout=5)
+
+
+# -- channel unit --------------------------------------------------------------
+
+
+async def test_dispatcher_answers_instead_of_wedging(tmp_path):
+ dispatcher = ch.AsgiDispatcher(_box_app(tmp_path, "d-data"))
+ try:
+ ok = await dispatcher.dispatch(
+ {"type": "rpc", "id": "r1", "method": "GET", "path": "/v1/health"}
+ )
+ assert ok["status"] == 200 and ok["id"] == "r1"
+ missing = await dispatcher.dispatch(
+ {"type": "rpc", "id": "r2", "method": "GET", "path": "/v1/nope"}
+ )
+ assert missing["status"] == 404
+ body = json.dumps({"name": "x"}).encode()
+ posted = await dispatcher.dispatch(
+ {
+ "type": "rpc",
+ "id": "r3",
+ "method": "POST",
+ "path": "/v1/workspaces/open",
+ "body_b64": ch.encode_body(body),
+ "content_type": "application/json",
+ }
+ )
+ assert posted["id"] == "r3" and posted["status"] in (200, 400, 422)
+ finally:
+ await dispatcher.aclose()
+
+
+def test_cli_status_and_leave(tmp_path, capsys, monkeypatch):
+ from coworker.remote import joiner
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "cli-state"))
+ assert joiner.cli(["status"]) == 0
+ out = capsys.readouterr().out
+ assert "not joined" in out and "none (created on first join)" in out
+
+ # `up` before any join is a clear error, not a crash.
+ assert joiner.cli(["up"]) == 2
+ assert "has not joined" in capsys.readouterr().err
+
+ state = Path(tmp_path / "cli-state")
+ state.mkdir(parents=True, exist_ok=True)
+ load_or_create(state)
+ joiner.save_remote_config(
+ state, {"controller": "http://10.0.0.5:9787", "name": "box", "machine_id": "m1"}
+ )
+ assert joiner.cli(["status"]) == 0
+ out = capsys.readouterr().out
+ assert "http://10.0.0.5:9787" in out and "ed25519" in out
+
+ assert joiner.cli(["leave", "--yes"]) == 0
+ assert not (state / "machine.key").exists()
+ assert joiner.load_remote_config(state) is None
+ assert joiner.cli(["status"]) == 0
+ assert "not joined" in capsys.readouterr().out
+
+
+def test_openworker_cli_routes_remote_verbs(monkeypatch, tmp_path, capsys):
+ from coworker import cli as ow_cli
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "route-state"))
+ with pytest.raises(SystemExit) as exit_info:
+ ow_cli.main(["status"])
+ assert exit_info.value.code == 0
+ assert "not joined" in capsys.readouterr().out
+
+
+def test_join_cli_bad_url_is_a_clear_error(monkeypatch, tmp_path, capsys):
+ from coworker.remote import joiner
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path / "bad-state"))
+ assert joiner.cli(["join", "http://host:1/wrong/tok"]) == 2
+ assert "join URL" in capsys.readouterr().err
+
+
+async def test_rpc_client_close_fails_pending():
+ sent = []
+
+ async def send(text):
+ sent.append(text)
+
+ client = ch.RpcClient(send)
+ request = asyncio.create_task(client.request("GET", "/v1/health"))
+ await asyncio.sleep(0.01)
+ client.close()
+ with pytest.raises(ConnectionError):
+ await request
+ with pytest.raises(ConnectionError):
+ await client.request("GET", "/v1/health")
+
+
+# -- cloud-mode skeleton (acceptor-only service) --------------------------------
+
+
+def test_desktop_capabilities_mode():
+ from fastapi.testclient import TestClient
+
+ import tempfile
+
+ manager = SessionManager(data_dir=Path(tempfile.mkdtemp()))
+ client = TestClient(create_app(manager))
+ assert client.get("/v1/capabilities").json() == {"mode": "desktop"}
+
+
+async def test_cloud_service_accepts_joins_and_proxies(tmp_path):
+ """The acceptor-as-module payoff: the SAME box code joins the cloud service,
+ which has no engine of its own — and the SPA-facing surface answers in
+ cloud mode with honest emptiness for local-only endpoints."""
+ from coworker.remote.service import create_cloud_app
+
+ async with _Server(create_cloud_app(tmp_path / "cloud")) as server:
+ async with httpx.AsyncClient() as client:
+ caps = await client.get(f"{server.base}/v1/capabilities")
+ assert caps.json() == {"mode": "cloud"}
+ health = await client.get(f"{server.base}/v1/health")
+ assert health.json()["status"] == "ok"
+ local = await client.get(f"{server.base}/v1/sessions")
+ assert local.json() == {"sessions": []} # a cloud has no LOCAL home
+
+ task, _ = await _join_box(tmp_path, server.base)
+ try:
+ machines = await _wait_connected(server.base)
+ mid = machines[0]["id"]
+ async with httpx.AsyncClient() as client:
+ # The box's surface through the CLOUD's proxy — identical to desktop.
+ proxied = await client.get(
+ f"{server.base}/v1/machines/{mid}/p/v1/health"
+ )
+ assert proxied.status_code == 200
+ # No wallet on the cloud tier (browser sealing lands later):
+ # deploys refuse rather than holding plaintext keys server-side.
+ deploy = await client.post(
+ f"{server.base}/v1/machines/{mid}/secrets",
+ json={"profiles": ["provider:openai"]},
+ )
+ assert deploy.status_code == 500
+ assert "no wallet" in deploy.json()["error"]
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_cloud_service_token_gate(tmp_path, monkeypatch):
+ from coworker.remote.service import create_cloud_app
+
+ monkeypatch.setenv("COWORKER_API_TOKEN", "cloud-secret")
+ async with _Server(create_cloud_app(tmp_path / "cloud")) as server:
+ async with httpx.AsyncClient() as client:
+ open_paths = await client.get(f"{server.base}/v1/health")
+ assert open_paths.status_code == 200
+ denied = await client.get(f"{server.base}/v1/machines")
+ assert denied.status_code == 401
+ allowed = await client.get(
+ f"{server.base}/v1/machines",
+ headers={"x-openworker-token": "cloud-secret"},
+ )
+ assert allowed.status_code == 200
+ # Machine-facing device-flow halves are tokenless (a box holds no
+ # dashboard token); approval is not.
+ start = await client.post(
+ f"{server.base}/v1/remote/device/start", json={"name": "vm"}
+ )
+ assert start.status_code == 200
+ poll = await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start.json()["device_code"]},
+ )
+ assert poll.status_code == 200 and poll.json()["status"] == "pending"
+ gated = await client.post(
+ f"{server.base}/v1/remote/device/{start.json()['user_code']}/approve"
+ )
+ assert gated.status_code == 401
+
+
+def test_audit_log_ocsf_shape_and_write_failure(tmp_path):
+ from coworker.remote.audit import AuditLog
+
+ log = AuditLog(tmp_path / "audit.jsonl")
+ log.emit(
+ "create",
+ entity_type="machine",
+ entity_name="my-box",
+ entity_uid="m1",
+ detail={"fingerprint": "abcd"},
+ )
+ event = json.loads((tmp_path / "audit.jsonl").read_text())
+ assert event["class_uid"] == 3004 and event["category_uid"] == 3
+ assert event["activity_id"] == 1 and event["type_uid"] == 300401
+ assert event["entity"] == {"type": "machine", "name": "my-box", "uid": "m1"}
+ assert event["metadata"]["product"]["name"] == "OpenWorker"
+ assert event["unmapped"] == {"fingerprint": "abcd"}
+ assert event["time"] > 0 and event["status_id"] == 1
+ # A write failure never breaks the audited action — it is counted instead.
+ # mkdir under a path that is a FILE fails with OSError.
+ broken = AuditLog(tmp_path / "audit.jsonl" / "not-a-dir" / "x.jsonl")
+ broken.emit("delete", entity_type="machine", entity_name="gone")
+ assert broken.dropped == 1
+
+
+def test_local_provisioner_launch_is_byo_only(tmp_path):
+ from coworker.remote.provision import LocalProvisioner
+ from coworker.remote.acceptor import RemoteAcceptor
+
+ prov = LocalProvisioner(RemoteAcceptor(MachinesRegistry(tmp_path / "db")))
+ minted = prov.mint_token({"fingerprint": "fp"})
+ assert minted["token"] and minted["expires_at"] > 0
+ with pytest.raises(NotImplementedError):
+ asyncio.run(prov.launch({"image": "whatever"}))
+
+
+# -- multi-tenancy ---------------------------------------------------------------
+
+
+async def _tenant_header_resolver(conn):
+ """Test resolver: the x-org header IS the tenant (a real deployment
+ verifies a JWT here). Async on purpose — the hosted resolver awaits its
+ IdP, so the whole multi-tenant suite exercises the await path."""
+ org = conn.headers.get("x-org")
+ if not org:
+ return None
+ return {"org_id": org, "actor": f"{org}-admin"}
+
+
+def _tenant_app(tmp_path):
+ from fastapi import FastAPI
+
+ from coworker.remote.acceptor import mount_acceptor
+ from coworker.remote.audit import AuditLog
+
+ app = FastAPI()
+ registry = MachinesRegistry(tmp_path / "tenant.db")
+ mount_acceptor(
+ app,
+ registry,
+ tenant_resolver=_tenant_header_resolver,
+ audit=AuditLog(tmp_path / "tenant-audit.jsonl"),
+ )
+ return app, registry
+
+
+async def test_multi_tenant_org_isolation(tmp_path):
+ """The SOC2 standing test: org B can neither see nor touch org A's machine
+ through ANY control-plane surface — every route answers 404, exactly as if
+ the machine did not exist."""
+ import websockets
+
+ app, registry = _tenant_app(tmp_path)
+ async with _Server(app) as server:
+ A, B = {"x-org": "org-a"}, {"x-org": "org-b"}
+ async with httpx.AsyncClient() as client:
+ # No tenant → 401 before anything else.
+ assert (await client.get(f"{server.base}/v1/machines")).status_code == 401
+ assert (
+ await client.post(f"{server.base}/v1/remote/arm")
+ ).status_code == 401
+ join_url = (
+ await client.post(f"{server.base}/v1/remote/arm", headers=A)
+ ).json()["join_url"]
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "a-box-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="a-box",
+ token=token,
+ app=_box_app(tmp_path, "a-box-data"),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ async with httpx.AsyncClient() as client:
+ deadline = asyncio.get_running_loop().time() + 5
+ while True:
+ rows = (
+ await client.get(f"{server.base}/v1/machines", headers=A)
+ ).json()["machines"]
+ if any(m["connected"] for m in rows):
+ break
+ assert asyncio.get_running_loop().time() < deadline
+ await asyncio.sleep(0.05)
+ mid = rows[0]["id"]
+ # The token carried org-a; the machine landed there.
+ assert registry.by_id(mid)["org_id"] == "org-a"
+ # B's listing is empty; every scoped surface 404s for B.
+ assert (
+ await client.get(f"{server.base}/v1/machines", headers=B)
+ ).json()["machines"] == []
+ for method, url, kwargs in [
+ ("GET", f"/v1/machines/{mid}/sessions", {}),
+ ("GET", f"/v1/machines/{mid}/sessions/s1/messages", {}),
+ ("GET", f"/v1/machines/{mid}/p/v1/health", {}),
+ ("PATCH", f"/v1/machines/{mid}", {"json": {"name": "hijack"}}),
+ ("DELETE", f"/v1/machines/{mid}", {}),
+ ("GET", f"/v1/machines/{mid}/secrets", {}),
+ ("POST", f"/v1/machines/{mid}/secrets", {"json": {"profiles": ["openai"]}}),
+ ]:
+ resp = await client.request(
+ method, f"{server.base}{url}", headers=B, **kwargs
+ )
+ assert resp.status_code == 404, (method, url, resp.status_code)
+ # The owner org works normally through the same routes.
+ ok = await client.get(
+ f"{server.base}/v1/machines/{mid}/p/v1/health", headers=A
+ )
+ assert ok.status_code == 200
+ # Bridged WebSocket from the wrong org is refused outright.
+ bridge = (
+ server.base.replace("http://", "ws://")
+ + f"/ws/machines/{mid}/p/ws/session/x"
+ )
+ with pytest.raises(websockets.InvalidStatus):
+ async with websockets.connect(bridge, additional_headers=B):
+ pass
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_multi_tenant_device_flow_claims_approver_org(tmp_path):
+ """`auth join` in a shared deployment: pending grants are unlisted (typed
+ code only), approval claims the grant into the APPROVER's org, and both the
+ approval and the enrollment land in the audit trail with that tenant."""
+ import websockets
+
+ app, registry = _tenant_app(tmp_path)
+ async with _Server(app) as server:
+ B = {"x-org": "org-b"}
+ box = load_or_create(tmp_path / "dev-box-state")
+ ws_url = server.base.replace("http://", "ws://") + "/ws/machine"
+ async with httpx.AsyncClient() as client:
+ start = (
+ await client.post(
+ f"{server.base}/v1/remote/device/start",
+ json={"name": "vmx", "fingerprint": box.fingerprint},
+ )
+ ).json()
+ # No cross-tenant listing of pending grants.
+ assert (
+ await client.get(f"{server.base}/v1/remote/device", headers=B)
+ ).status_code == 404
+ # Typed code → the machine's claimed identity, for the user to verify.
+ detail = (
+ await client.get(
+ f"{server.base}/v1/remote/device/{start['user_code']}", headers=B
+ )
+ ).json()
+ assert detail["name"] == "vmx"
+ assert detail["fingerprint"] == box.fingerprint
+ # Approval requires a tenant — the org is what approval claims.
+ assert (
+ await client.post(
+ f"{server.base}/v1/remote/device/{start['user_code']}/approve"
+ )
+ ).status_code == 401
+ assert (
+ await client.post(
+ f"{server.base}/v1/remote/device/{start['user_code']}/approve",
+ headers=B,
+ )
+ ).status_code == 200
+ poll = (
+ await client.post(
+ f"{server.base}/v1/remote/device/poll",
+ json={"device_code": start["device_code"]},
+ )
+ ).json()
+ _, token = parse_join_url(poll["join_url"])
+ async with websockets.connect(ws_url) as ws:
+ frame = await _wire_join(
+ ws,
+ box,
+ token=token,
+ seal_pubkey=box.seal_public_key_b64,
+ seal_sig=box.attest_seal_key_b64(),
+ )
+ assert frame["type"] == "welcome"
+ assert registry.by_pubkey(box.public_key_b64)["org_id"] == "org-b"
+ events = [
+ json.loads(line)
+ for line in (tmp_path / "tenant-audit.jsonl").read_text().splitlines()
+ ]
+ approve = next(e for e in events if e["entity"]["type"] == "device_grant")
+ assert approve["actor"]["user"]["name"] == "org-b-admin"
+ assert approve["actor"]["user"]["org"]["uid"] == "org-b"
+ enroll = next(e for e in events if e["entity"]["type"] == "machine")
+ assert enroll["actor"]["user"]["org"]["uid"] == "org-b"
+
+
+# -- service install (systemd) --------------------------------------------------
+
+
+def test_systemd_unit_content(tmp_path):
+ from coworker.remote.joiner import _systemd_unit
+
+ unit = _systemd_unit(tmp_path / "state", "/usr/local/bin/openworker")
+ assert "ExecStart=/usr/local/bin/openworker up" in unit
+ assert f"Environment=COWORKER_STATE_DIR={tmp_path / 'state'}" in unit
+ assert "Restart=always" in unit
+ assert "WantedBy=default.target" in unit
+
+
+def test_service_install_refuses_non_linux_and_unjoined(tmp_path, capsys):
+ import argparse
+
+ from coworker.remote import joiner
+
+ args = argparse.Namespace(service_command="install")
+ # Not Linux → clear refusal.
+ assert joiner._cmd_service(tmp_path, args, platform="darwin", home=tmp_path) == 2
+ assert "targets Linux/systemd" in capsys.readouterr().err
+ # Linux but never joined → point at `join` first.
+ assert joiner._cmd_service(tmp_path, args, platform="linux", home=tmp_path) == 2
+ assert "has not joined" in capsys.readouterr().err
+
+
+def test_service_install_writes_unit_and_uninstall_removes(tmp_path, capsys):
+ import argparse
+
+ from coworker.remote import joiner
+
+ state = tmp_path / "state"
+ state.mkdir()
+ joiner.save_remote_config(
+ state, {"controller": "http://10.0.0.5:8765", "name": "vm", "machine_id": "m1"}
+ )
+ args = argparse.Namespace(service_command="install")
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ # Named after the joined identity, never the bare legacy name.
+ unit = tmp_path / ".config" / "systemd" / "user" / "openworker-vm.service"
+ assert unit.exists()
+ text = unit.read_text()
+ assert f"COWORKER_STATE_DIR={state}" in text
+ assert " up" in text
+ assert "(vm)" in text
+ out = capsys.readouterr().out
+ assert "wrote" in out # systemctl may be absent here; manual fallback printed
+
+ args = argparse.Namespace(service_command="uninstall", unit=None)
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ assert not unit.exists()
+
+
+def _joined_state(tmp_path, name, controller="http://10.0.0.5:8765"):
+ from coworker.remote import joiner
+
+ state = tmp_path / f"state-{name}"
+ state.mkdir()
+ joiner.save_remote_config(
+ state, {"controller": controller, "name": name, "machine_id": f"m-{name}"}
+ )
+ return state
+
+
+def test_service_install_refuses_twin_on_same_state_dir(tmp_path, capsys):
+ """The VM bug: a stale unit still pinned to the state dir we are installing
+ for — two `up` engines, one SQLite, and every kill undone by Restart=always.
+ Install refuses and names the twin; --force replaces it."""
+ import argparse
+
+ from coworker.remote import joiner
+
+ state = _joined_state(tmp_path, "cloud-vm")
+ unit_dir = tmp_path / ".config" / "systemd" / "user"
+ unit_dir.mkdir(parents=True)
+ stale = unit_dir / "openworker.service"
+ stale.write_text(joiner._systemd_unit(state, "/old/openworker"))
+
+ args = argparse.Namespace(service_command="install", force=False)
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 2
+ err = capsys.readouterr().err
+ assert "openworker.service already runs" in err
+ assert "--unit openworker.service" in err
+ assert not (unit_dir / "openworker-cloud-vm.service").exists()
+
+ args = argparse.Namespace(service_command="install", force=True)
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ out = capsys.readouterr().out
+ assert "replaced openworker.service" in out
+ assert not stale.exists()
+ assert (unit_dir / "openworker-cloud-vm.service").exists()
+
+
+def test_service_install_reports_other_engine_and_list_shows_all(tmp_path, capsys):
+ import argparse
+
+ from coworker.remote import joiner
+
+ other_state = _joined_state(tmp_path, "my-box", controller="http://127.0.0.1:8765")
+ state = _joined_state(tmp_path, "cloud-vm")
+ unit_dir = tmp_path / ".config" / "systemd" / "user"
+ unit_dir.mkdir(parents=True)
+ (unit_dir / "openworker-my-box.service").write_text(
+ joiner._systemd_unit(other_state, "/x/openworker", "my-box")
+ )
+
+ args = argparse.Namespace(service_command="install", force=False)
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ out = capsys.readouterr().out
+ assert "note: openworker-my-box.service is also installed" in out
+ assert str(other_state) in out
+
+ args = argparse.Namespace(service_command="list")
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ out = capsys.readouterr().out
+ assert "openworker-cloud-vm.service" in out and "openworker-my-box.service" in out
+ assert str(state) in out and str(other_state) in out
+
+ # Uninstall by explicit unit name removes the stale twin, not ours.
+ args = argparse.Namespace(service_command="uninstall", unit="openworker-my-box.service")
+ assert joiner._cmd_service(state, args, platform="linux", home=tmp_path) == 0
+ assert not (unit_dir / "openworker-my-box.service").exists()
+ assert (unit_dir / "openworker-cloud-vm.service").exists()
+
+
+def test_unit_name_for_slugs_and_falls_back():
+ from coworker.remote.joiner import SERVICE_UNIT_NAME, unit_name_for
+
+ assert unit_name_for("cloud-vm") == "openworker-cloud-vm.service"
+ assert unit_name_for("Rohit's box #2") == "openworker-Rohit-s-box--2.service"
+ assert unit_name_for("") == SERVICE_UNIT_NAME
+
+
+def test_up_refuses_when_another_engine_holds_the_state_dir(tmp_path, capsys):
+ """`openworker up` on a state dir another engine holds must stop and say so —
+ never dial the controller as a second engine."""
+ from coworker import statelock
+ from coworker.remote import joiner
+
+ state = _joined_state(tmp_path, "cloud-vm")
+ held = statelock.acquire(state)
+ try:
+ rc = joiner._run(state, "http://10.0.0.5:8765", "cloud-vm")
+ finally:
+ held.release()
+ assert rc == 3
+ err = capsys.readouterr().err
+ assert "another engine" in err and str(state) in err
+
+
+# -- union view: the desktop's cloud proxy (spec §"Union view on the signed-in
+# desktop") — /v1/cloud/machines* forwards to the hosted service with the
+# stored cloud session token; session problems degrade, never error. ----------
+
+
+def _proxy_app(base_url, *, state="ok", token="cloud-token", wallet=None):
+ from fastapi import FastAPI
+
+ from coworker.remote.cloudproxy import mount_cloud_proxy
+
+ app = FastAPI()
+
+ async def provider():
+ return (state, token if state == "ok" else None)
+
+ mount_cloud_proxy(
+ app, token_provider=provider, base_url=base_url, wallet=wallet
+ )
+ return app
+
+
+async def test_cloud_proxy_session_states():
+ """Signed out / expired are STATES the GUI renders, not errors: the list
+ answers 200 with the state, per-machine calls answer 401 carrying it."""
+ for state in ("signed_out", "expired"):
+ app = _proxy_app("http://cloud.invalid", state=state)
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
+ body = (await c.get("/v1/cloud/machines")).json()
+ assert body == {"session": state, "machines": []}
+ r = await c.get("/v1/cloud/machines/m1/p/v1/settings")
+ assert r.status_code == 401
+ assert r.json()["session"] == state
+
+
+async def test_cloud_proxy_union_end_to_end(tmp_path):
+ """A real upstream controller + joined box, reached THROUGH the proxy:
+ the machines list forwards the bearer, the engine proxy round-trips,
+ wallet-send seals LOCALLY (upstream relays ciphertext — its audit says
+ browser-sealed and the box's store receives the plaintext copy), and the
+ bridged WS pipes a full scripted turn."""
+ import websockets
+
+ class _StubWallet:
+ def __init__(self, rows):
+ self._rows = rows
+
+ def get(self, name):
+ return self._rows.get(name)
+
+ upstream_manager = SessionManager(
+ workspace=tmp_path / "ws", data_dir=tmp_path / "up"
+ )
+ async with _Server(create_app(upstream_manager)) as upstream:
+ join_url = await _arm(upstream.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "union-state"
+ state.mkdir()
+ from coworker.providers import AssistantTurn
+
+ (tmp_path / "union-ws").mkdir(exist_ok=True)
+ box_manager = SessionManager(
+ workspace=tmp_path / "union-ws",
+ data_dir=tmp_path / "union-data",
+ provider=_scripted_provider(
+ [AssistantTurn(text="Hello via the union.", finish_reason="stop")]
+ ),
+ )
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=upstream.base,
+ name="union-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ wallet = _StubWallet({"openai": {"api_key": "sk-cloudkey"}})
+ try:
+ await _wait_connected(upstream.base)
+ async with _Server(
+ _proxy_app(upstream.base, wallet=wallet)
+ ) as proxy:
+ async with httpx.AsyncClient() as c:
+ listing = (
+ await c.get(f"{proxy.base}/v1/cloud/machines")
+ ).json()
+ assert listing["session"] == "ok"
+ assert len(listing["machines"]) == 1
+ mid = listing["machines"][0]["id"]
+
+ # Engine proxy round-trip through BOTH hops.
+ health = await c.get(
+ f"{proxy.base}/v1/cloud/machines/{mid}/p/v1/health"
+ )
+ assert health.status_code == 200
+
+ # Wallet-send: names in, sealed out. The box's own store
+ # receives the copy; the upstream audit shows the sealed
+ # (blind-relay) branch was taken — it never saw plaintext.
+ resp = await c.post(
+ f"{proxy.base}/v1/cloud/machines/{mid}/secrets",
+ json={"profiles": ["openai"]},
+ )
+ assert resp.status_code == 200
+ assert box_manager.secrets.get("openai") == {
+ "api_key": "sk-cloudkey"
+ }
+ audit_path = tmp_path / "up" / "remote-audit.jsonl"
+ events = [
+ json.loads(line)
+ for line in audit_path.read_text().splitlines()
+ ]
+ deploy = next(
+ e
+ for e in events
+ if e["entity"]["type"] == "secret_deploy"
+ )
+ assert deploy["unmapped"]["source"] == "browser-sealed"
+
+ # Missing wallet profile is the caller's error, not a relay.
+ missing = await c.post(
+ f"{proxy.base}/v1/cloud/machines/{mid}/secrets",
+ json={"profiles": ["nope"]},
+ )
+ assert missing.status_code == 400
+
+ # Bridged WS through the proxy: a scripted turn runs on the box.
+ bridge_url = (
+ proxy.base.replace("http://", "ws://")
+ + f"/ws/cloud/machines/{mid}/p/ws/session/union-chat-1"
+ )
+ async with websockets.connect(
+ bridge_url, subprotocols=["openworker"]
+ ) as ws:
+ first = json.loads(await ws.recv())
+ assert first["type"] == "ready"
+ await ws.send(
+ json.dumps({"type": "user_message", "text": "hi"})
+ )
+ texts, done = [], False
+ while not done:
+ event = json.loads(
+ await asyncio.wait_for(ws.recv(), timeout=10)
+ )
+ if event["type"] == "assistant_message":
+ texts.append(event["data"]["text"])
+ done = event["type"] == "turn_done"
+ assert texts == ["Hello via the union."]
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_sealed_connector_connect_end_to_end(tmp_path):
+ """Remote manual connect: fields sealed to the machine's pinned key, the
+ controller relays ciphertext, the BOX unseals and runs its own connect
+ (validation included) — the profile lands in the box's store and the
+ audit trail records the connector NAME only."""
+ from coworker.connectors import descriptors as _desc
+ from coworker.connectors.descriptors import (
+ ConnectorDescriptor,
+ Field,
+ ValidationResult,
+ )
+ from coworker.remote.identity import seal_b64
+
+ d = ConnectorDescriptor(
+ name="sealtestapp",
+ title="SealTest",
+ icon="◇",
+ blurb="test connector",
+ auth="api_token",
+ two_way=False,
+ fields=[Field("api_key", "API key", secret=True)],
+ instructions=[],
+ validate=lambda creds: ValidationResult(True, identity="[email protected]"),
+ )
+ _desc.register_descriptor(d)
+ try:
+ upstream_manager = SessionManager(
+ workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl"
+ )
+ async with _Server(create_app(upstream_manager)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "sc-state"
+ state.mkdir()
+ box_manager = SessionManager(data_dir=tmp_path / "sc-data")
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="seal-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ row = machines[0]
+ sealed = seal_b64(
+ row["seal_pubkey"],
+ json.dumps({"fields": {"api_key": "sk-sealed-connect"}}).encode(),
+ )
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ f"{server.base}/v1/machines/{row['id']}/connectors/"
+ "sealtestapp/connect-sealed",
+ json={"sealed_b64": sealed},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["ok"] is True
+ # The BOX holds the credential, validated (account resolved).
+ # (No controller-side negative here: this rig's SessionManagers
+ # share the default SecretStore path — a known test artifact.)
+ stored = box_manager.secrets.get("sealtestapp:default") or {}
+ assert stored.get("api_key") == "sk-sealed-connect"
+ assert stored.get("account") == "[email protected]"
+ # Audit: connector name only, sealed source, never the fields.
+ audit_text = (tmp_path / "ctrl" / "remote-audit.jsonl").read_text()
+ assert "sealtestapp" in audit_text
+ assert "sk-sealed-connect" not in audit_text
+ # A garbage blob is the box's 400, not a relay error.
+ async with httpx.AsyncClient() as client:
+ bad = await client.post(
+ f"{server.base}/v1/machines/{row['id']}/connectors/"
+ "sealtestapp/connect-sealed",
+ json={"sealed_b64": "not-a-blob"},
+ )
+ assert bad.status_code == 400
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ _desc.DESCRIPTORS.remove(d)
+ _desc._BY_NAME.pop(d.name, None)
+
+
+async def test_machine_targeted_oauth_callback_lands_grant_on_box(tmp_path, monkeypatch):
+ """Connect-direct-to-machine (machines spec §Remote OAuth): the broker's
+ callback hits the DESKTOP as usual, but the pending record names a target
+ machine — so the grant is delegated, staged in memory, sealed to the box's
+ pinned key, and deployed. The desktop store never holds it."""
+ from coworker import cloud
+ from coworker.secrets import SecretStore
+
+ upstream_manager = SessionManager(
+ workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl"
+ )
+ # The rig's managers share the default SecretStore path; give each its own
+ # so "the desktop holds nothing" is a real assertion.
+ upstream_manager.secrets = SecretStore(tmp_path / "ctrl-secrets.json")
+ box_manager = SessionManager(data_dir=tmp_path / "box-data")
+ box_manager.secrets = SecretStore(tmp_path / "box-secrets.json")
+
+ monkeypatch.setattr(
+ cloud,
+ "delegate_connection",
+ lambda *a, **k: {"user_id": "usr_delegated", "machine_credential": "mc_test"},
+ )
+
+ async with _Server(create_app(upstream_manager)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "grant-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="grant-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ row = machines[0]
+ cloud._pending_managed_states["mt"] = {
+ "created": cloud._now(),
+ "machine_id": row["id"],
+ "machine_name": "grant-box",
+ }
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ f"{server.base}/oauth/callback",
+ data={
+ "provider": "notion",
+ "connector": "notion",
+ "connection_id": "conn_target",
+ "access_token": "secret-access",
+ "refresh_token": "secret-refresh",
+ "account": "Acme Workspace",
+ "account_id": "ws_1",
+ "app_state": "mt",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert "connected on grant-box" in resp.text
+
+ # The BOX holds the grant, delegation id included (what the box's
+ # possession-based renewal needs), via its own accounts layer.
+ stored = box_manager.secrets.get("notion:account:ws_1") or {}
+ assert stored.get("access_token") == "secret-access"
+ assert stored.get("refresh_token") == "secret-refresh"
+ assert stored.get("connection_id") == "conn_target"
+ assert stored.get("broker_user_id") == "usr_delegated"
+ # The machine credential (spec §Managed events) rides along.
+ assert stored.get("machine_credential") == "mc_test"
+ assert (box_manager.secrets.get("notion:default") or {}).get(
+ "default_account"
+ ) == "ws_1"
+ # One grant, one holder: the desktop stored nothing.
+ assert upstream_manager.secrets.get("notion:default") is None
+ assert upstream_manager.secrets.get("notion:account:ws_1") is None
+
+ # Ledger + audit: profile NAMES only, never token values.
+ async with httpx.AsyncClient() as client:
+ ledger = await client.get(
+ f"{server.base}/v1/machines/{row['id']}/secrets"
+ )
+ names = {r["profile"] for r in ledger.json()["secrets"]}
+ assert "notion:account:ws_1" in names
+ audit_text = (tmp_path / "ctrl" / "remote-audit.jsonl").read_text()
+ assert "notion:account:ws_1" in audit_text
+ assert "secret-access" not in audit_text
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_machine_targeted_github_callback_stages_all_installs(tmp_path, monkeypatch):
+ """Connect-direct for GitHub (increment 2): the install-flow callback
+ stages EVERY returned installation — the same unit a Move ships — plus
+ the stamped pointer, all metadata + credential, no secrets anywhere."""
+ from coworker import cloud
+ from coworker.secrets import SecretStore
+
+ upstream_manager = SessionManager(
+ workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl"
+ )
+ upstream_manager.secrets = SecretStore(tmp_path / "ctrl-secrets.json")
+ box_manager = SessionManager(data_dir=tmp_path / "box-data")
+ box_manager.secrets = SecretStore(tmp_path / "box-secrets.json")
+
+ monkeypatch.setattr(
+ cloud,
+ "delegate_connection",
+ lambda *a, **k: {"user_id": "usr_gh", "machine_credential": "mc_gh"},
+ )
+
+ async with _Server(create_app(upstream_manager)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "gh-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state,
+ controller=server.base,
+ name="gh-box",
+ token=token,
+ app=create_app(box_manager),
+ once=True,
+ log=lambda *_: None,
+ )
+ )
+ try:
+ machines = await _wait_connected(server.base)
+ row = machines[0]
+ cloud._pending_managed_states["ghm"] = {
+ "created": cloud._now(),
+ "machine_id": row["id"],
+ "machine_name": "gh-box",
+ }
+ installs = [
+ {"installation_id": "9001", "account_login": "quillvoice",
+ "account_type": "Organization", "repo_selection": "selected"},
+ {"installation_id": "9002", "account_login": "rohit",
+ "account_type": "User", "repo_selection": "all"},
+ ]
+ async with httpx.AsyncClient() as client:
+ resp = await client.post(
+ f"{server.base}/oauth/callback",
+ data={
+ "provider": "github",
+ "connector": "github",
+ "connection_id": "conn_gh",
+ "installation_id": "9001",
+ "account_login": "quillvoice",
+ "account_type": "Organization",
+ "repo_selection": "selected",
+ "github_login": "rohit",
+ "installations": json.dumps(installs),
+ "app_state": "ghm",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+ assert "connected on gh-box" in resp.text
+
+ # The BOX holds BOTH installations + the stamped pointer.
+ for iid in ("9001", "9002"):
+ prof = box_manager.secrets.get(f"github:install:{iid}") or {}
+ assert prof.get("machine_credential") == "mc_gh"
+ assert prof.get("broker_user_id") == "usr_gh"
+ pointer = box_manager.secrets.get("github:default") or {}
+ assert pointer.get("mode") == "relay"
+ assert pointer.get("connection_id") == "conn_gh"
+ assert pointer.get("machine_credential") == "mc_gh"
+ # The desktop stored nothing; no secrets exist anywhere to leak.
+ assert upstream_manager.secrets.get("github:default") is None
+ assert upstream_manager.secrets.get("github:install:9001") is None
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+# -- fleet under the org: machine owner + session actor (spec 2026-09-02) -------
+
+
+async def test_enrollment_records_owner_and_bridged_sessions_carry_the_actor(tmp_path):
+ """The member who armed the join owns the machine; a session opened through
+ the controller is stamped with the controller-verified login (first writer
+ wins) and every audit row of that session names them."""
+ import websockets
+
+ from coworker.sessions import SessionRecord
+
+ app, registry = _tenant_app(tmp_path)
+ async with _Server(app) as server:
+ async with httpx.AsyncClient() as client:
+ join_url = (
+ await client.post(f"{server.base}/v1/remote/arm", headers={"x-org": "acme"})
+ ).json()["join_url"]
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "owner-state"
+ state.mkdir()
+ box_manager = SessionManager(data_dir=tmp_path / "owner-data")
+ task = asyncio.create_task(
+ run_joined(
+ state=state, controller=server.base, name="owned", token=token,
+ app=create_app(box_manager), once=True, log=lambda *_: None,
+ )
+ )
+ try:
+ async with httpx.AsyncClient() as client:
+ rows = []
+ for _ in range(100):
+ rows = (await client.get(f"{server.base}/v1/machines", headers={"x-org": "acme"})).json()["machines"]
+ if rows and rows[0]["connected"]:
+ break
+ await asyncio.sleep(0.05)
+ assert rows[0]["enrolled_by"] == "acme-admin"
+ assert registry.by_id(rows[0]["id"])["enrolled_by"] == "acme-admin"
+ mid = rows[0]["id"]
+
+ # A bridged session socket: the controller stamps the actor it verified.
+ ws_url = server.base.replace("http://", "ws://") + f"/ws/machines/{mid}/p/ws/session/s-owned?agent=cowork"
+ async with websockets.connect(ws_url, additional_headers={"x-org": "acme"}) as ws:
+ frame = json.loads(await ws.recv())
+ assert frame["type"] == "ready"
+ assert box_manager.session_actor("s-owned") == "acme-admin"
+ # First writer wins: a second viewer never rewrites who started it.
+ box_manager.note_session_actor("s-owned", "someone-else")
+ assert box_manager.session_actor("s-owned") == "acme-admin"
+ # The engine's audit sink stamps the actor; the persisted record carries it.
+ box_manager._audit_sink_for("s-owned")({"session_id": "s-owned", "tool": "run_shell", "arguments": {"command": "ls"}})
+ row = box_manager.audit_store.list(session_id="s-owned")[0]
+ assert row["actor"] == "acme-admin"
+ box_manager.session_store.save(SessionRecord(session_id="s-owned", workspace="", model="m", mode="interactive", actor=box_manager.session_actor("s-owned")))
+ assert box_manager.session_store.load("s-owned").actor == "acme-admin"
+ assert next(r for r in box_manager.list_sessions() if r["session_id"] == "s-owned")["actor"] == "acme-admin"
+ # A proxied REST call carries it too (header injected by the box's dispatcher only).
+ async with httpx.AsyncClient() as client:
+ r = await client.get(f"{server.base}/v1/machines/{mid}/p/v1/sessions", headers={"x-org": "acme"})
+ assert r.status_code == 200
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_managed_sandbox_token_stamps_provenance_on_the_enrolled_row(tmp_path):
+ """A provisioner mints the join token WITH a provenance; the box that joins
+ with it is recorded as that provisioner's machine (kind + the
+ provisioner's own id), so lifecycle code can find the box a sandbox
+ became. User-armed tokens leave both fields empty."""
+ app, registry = _tenant_app(tmp_path)
+ acceptor = app.state.remote_acceptor
+ async with _Server(app) as server:
+ token, _ = acceptor.arm(
+ org_id="acme", actor="acme-admin", provenance={"kind": "fly", "ref": "sb-1"}
+ )
+ state = tmp_path / "sandbox-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(
+ state=state, controller=server.base, name="sandbox-1", token=token,
+ app=create_app(SessionManager(data_dir=tmp_path / "sandbox-data")),
+ once=True, log=lambda *_: None,
+ )
+ )
+ try:
+ async with httpx.AsyncClient() as client:
+ rows = []
+ for _ in range(100):
+ rows = (await client.get(f"{server.base}/v1/machines", headers={"x-org": "acme"})).json()["machines"]
+ if rows and rows[0]["connected"]:
+ break
+ await asyncio.sleep(0.05)
+ assert (rows[0]["provenance"], rows[0]["provenance_ref"]) == ("fly", "sb-1")
+ assert rows[0]["enrolled_by"] == "acme-admin"
+ row = registry.by_id(rows[0]["id"])
+ assert (row["provenance"], row["provenance_ref"]) == ("fly", "sb-1")
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ # Brought-your-own rows stay unmarked.
+ assert registry.enroll("byo", "pk-byo", org_id="acme")["provenance"] == ""
+
+
+async def test_activity_and_wake_hooks_on_the_proxy(tmp_path):
+ """Managed sandboxes: every proxied call/socket touches `machine_activity`;
+ reaching an OFFLINE machine asks `machine_wake`, and when it says it
+ started the box, the call waits for the box to dial back in instead of
+ answering 503. A wake that declines keeps today's 503."""
+ from fastapi import FastAPI
+
+ from coworker.remote import acceptor as acc
+ from coworker.remote.acceptor import mount_acceptor
+
+ touched: list[str] = []
+ wake_calls: list[str] = []
+ registry = MachinesRegistry(tmp_path / "db")
+ app = FastAPI()
+ box_state = tmp_path / "sleepy-state"
+ box_state.mkdir()
+ box_app = create_app(SessionManager(data_dir=tmp_path / "sleepy-data"))
+ server_ref: dict[str, Any] = {}
+ box_task: dict[str, Any] = {}
+
+ async def wake(machine_id: str) -> bool:
+ wake_calls.append(machine_id)
+ if wake_calls.count(machine_id) > 1:
+ return False # second time: "not a sandbox" / could not start
+ # "Fly started it": the box dials back in a moment later.
+ box_task["t"] = asyncio.create_task(
+ run_joined(state=box_state, controller=server_ref["base"], name="sleepy",
+ app=box_app, once=True, log=lambda *_: None)
+ )
+ return True
+
+ mount_acceptor(app, registry, machine_activity=touched.append, machine_wake=wake)
+ acceptor = app.state.remote_acceptor
+ async with _Server(app) as server:
+ server_ref["base"] = server.base
+ # Enroll once so the row exists, then let the box go away.
+ token, _ = acceptor.arm()
+ first = asyncio.create_task(
+ run_joined(state=box_state, controller=server.base, name="sleepy", token=token,
+ app=box_app, once=True, log=lambda *_: None)
+ )
+ async with httpx.AsyncClient() as client:
+ mid = ""
+ for _ in range(100):
+ rows = (await client.get(f"{server.base}/v1/machines")).json()["machines"]
+ if rows and rows[0]["connected"]:
+ mid = rows[0]["id"]
+ break
+ await asyncio.sleep(0.05)
+ assert mid
+ r = await client.get(f"{server.base}/v1/machines/{mid}/p/v1/activity")
+ assert r.status_code == 200 and r.json()["running_sessions"] == 0
+ assert touched == [mid]
+ first.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await first
+ for _ in range(100):
+ if acceptor.live(mid) is None:
+ break
+ await asyncio.sleep(0.05)
+ assert acceptor.live(mid) is None
+ try:
+ async with httpx.AsyncClient(timeout=60) as client:
+ # Offline: the wake hook starts the box and the call waits for it.
+ r = await client.get(f"{server.base}/v1/machines/{mid}/p/v1/health")
+ assert r.status_code == 200, r.text
+ assert wake_calls == [mid]
+ finally:
+ t = box_task.get("t")
+ if t is not None:
+ t.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await t
+ for _ in range(100):
+ if acceptor.live(mid) is None:
+ break
+ await asyncio.sleep(0.05)
+ # Wake declined ⇒ plain offline answer, no waiting.
+ acc_wait = acc.WAKE_WAIT_SECONDS
+ acc.WAKE_WAIT_SECONDS = 0.2
+ try:
+ async with httpx.AsyncClient() as client:
+ r = await client.get(f"{server.base}/v1/machines/{mid}/p/v1/health")
+ assert r.status_code == 503
+ finally:
+ acc.WAKE_WAIT_SECONDS = acc_wait
+
+
+def test_local_sessions_have_no_actor_and_headers_are_not_trusted_locally(tmp_path):
+ """Desktop/local: no controller, no actor. The box-side dispatcher is the
+ ONLY place the header is minted; a stray header on the local sidecar is
+ ignored by the note (empty tenant) — nothing else reads it."""
+ from coworker.remote.channel import ACTOR_HEADER
+
+ manager = SessionManager(data_dir=tmp_path / "local")
+ manager.note_session_actor("local-1", "")
+ assert manager.session_actor("local-1") == ""
+ manager._audit_sink_for("local-1")({"session_id": "local-1", "tool": "read_file", "arguments": {}})
+ assert manager.audit_store.list(session_id="local-1")[0]["actor"] == ""
+ assert ACTOR_HEADER == "x-openworker-actor"
+
+
+async def test_browser_sealed_managed_grant_lands_on_the_box(tmp_path):
+ """Cloud-dashboard connect-direct (spec): the dashboard tab seals the
+ broker's callback result + delegation to the box's pinned key and posts
+ it to the acceptor, which relays ciphertext; the box stores it through
+ the shared bundle routine. The controller stores nothing readable."""
+ from coworker.remote.identity import seal_b64
+ from coworker.secrets import SecretStore
+
+ upstream = SessionManager(workspace=tmp_path / "ws", data_dir=tmp_path / "ctrl")
+ upstream.secrets = SecretStore(tmp_path / "ctrl-secrets.json")
+ box_manager = SessionManager(data_dir=tmp_path / "box-data")
+ box_manager.secrets = SecretStore(tmp_path / "box-secrets.json")
+ async with _Server(create_app(upstream)) as server:
+ join_url = await _arm(server.base)
+ _, token = parse_join_url(join_url)
+ state = tmp_path / "bs-state"
+ state.mkdir()
+ task = asyncio.create_task(
+ run_joined(state=state, controller=server.base, name="bs-box", token=token,
+ app=create_app(box_manager), once=True, log=lambda *_: None)
+ )
+ try:
+ row = (await _wait_connected(server.base))[0]
+ payload = {
+ "form": {
+ "provider": "notion", "connector": "notion", "connection_id": "conn_b",
+ "access_token": "secret-access", "refresh_token": "secret-refresh",
+ "account": "Acme", "account_id": "ws_9",
+ },
+ "machine_credential": "mc_browser",
+ "broker_user_id": "usr_browser",
+ }
+ sealed = seal_b64(row["seal_pubkey"], json.dumps(payload).encode())
+ async with httpx.AsyncClient() as client:
+ r = await client.post(
+ f"{server.base}/v1/machines/{row['id']}/connectors/notion/managed-grant-sealed",
+ json={"sealed_b64": sealed},
+ )
+ assert r.status_code == 200 and r.json().get("ok"), r.text
+ stored = box_manager.secrets.get("notion:account:ws_9") or {}
+ assert stored.get("access_token") == "secret-access"
+ assert stored.get("broker_user_id") == "usr_browser"
+ assert stored.get("machine_credential") == "mc_browser"
+ assert upstream.secrets.get("notion:account:ws_9") is None
+ audit_text = (tmp_path / "ctrl" / "remote-audit.jsonl").read_text()
+ assert "managed_grant" in audit_text and "secret-access" not in audit_text
+ # A bad payload is refused by the box, not stored.
+ bad = seal_b64(row["seal_pubkey"], json.dumps({"form": {"connector": "notion"}}).encode())
+ r = await client.post(
+ f"{server.base}/v1/machines/{row['id']}/connectors/notion/managed-grant-sealed",
+ json={"sealed_b64": bad},
+ )
+ assert r.status_code == 400
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
diff --git a/tests/test_statelock.py b/tests/test_statelock.py
new file mode 100644
index 00000000..814100f9
--- /dev/null
+++ b/tests/test_statelock.py
@@ -0,0 +1,87 @@
+"""One engine per state dir (coworker/statelock.py)."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+
+import pytest
+
+from coworker import statelock
+
+
+def test_second_acquire_in_process_is_refused_with_holder_pid(tmp_path):
+ first = statelock.acquire(tmp_path)
+ try:
+ assert (tmp_path / statelock.LOCK_NAME).read_text() == str(os.getpid())
+ with pytest.raises(statelock.EngineBusy) as exc:
+ statelock.acquire(tmp_path)
+ # Same process holds it; the message still says who, without claiming a foreign pid.
+ assert str(tmp_path) in str(exc.value)
+ finally:
+ first.release()
+ # Released → free again.
+ statelock.acquire(tmp_path).release()
+
+
+def test_lock_is_held_across_processes_and_names_the_holder(tmp_path):
+ """A second PROCESS (the systemd-twin case) is refused and told the holder's pid."""
+ holder = subprocess.Popen(
+ [
+ sys.executable,
+ "-c",
+ "import sys,time; from coworker import statelock; "
+ f"h=statelock.acquire({str(tmp_path)!r}); print('held',flush=True); time.sleep(30)",
+ ],
+ stdout=subprocess.PIPE,
+ text=True,
+ cwd=os.getcwd(),
+ )
+ try:
+ assert holder.stdout.readline().strip() == "held"
+ with pytest.raises(statelock.EngineBusy) as exc:
+ statelock.acquire(tmp_path, timeout=0.3)
+ assert exc.value.holder_pid == holder.pid
+ assert f"pid {holder.pid}" in str(exc.value)
+ finally:
+ holder.kill()
+ holder.wait()
+ # Holder gone → the lock is free; the stale pid file does not block anyone.
+ statelock.acquire(tmp_path).release()
+
+
+def test_acquire_waits_for_a_dying_predecessor(tmp_path):
+ """A supervisor restart may overlap the old process's teardown: the new one
+ waits up to `timeout` instead of failing on the first try."""
+ import threading
+ import time
+
+ first = statelock.acquire(tmp_path)
+ threading.Timer(0.4, first.release).start()
+ t0 = time.monotonic()
+ second = statelock.acquire(tmp_path, timeout=3.0)
+ try:
+ assert 0.3 <= time.monotonic() - t0 < 3.0
+ finally:
+ second.release()
+
+
+def test_server_entrypoint_warns_unless_strict(tmp_path, monkeypatch, capsys):
+ from coworker.server import run as server_run
+
+ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))
+ held = statelock.acquire(tmp_path)
+ try:
+ monkeypatch.delenv("COWORKER_STATE_LOCK", raising=False)
+ server_run._warn_if_state_shared() # coexisting desktop + hand-run server: warn only
+ assert "warning: another engine" in capsys.readouterr().err
+ monkeypatch.setenv("COWORKER_STATE_LOCK", "strict")
+ with pytest.raises(SystemExit) as exc:
+ server_run._warn_if_state_shared()
+ assert exc.value.code == 3
+ finally:
+ held.release()
+ if server_run._ENGINE_LOCK is not None:
+ server_run._ENGINE_LOCK.release()
+ server_run._ENGINE_LOCK = None