Files
gabrielvidalandClaude Opus 5.5 ad308d22e8 feat(workers): owner workers that dial out — for a machine off the tailnet
A worker on a network the hub can't call (an Orus devbox, only on the
company's tailnet) now pairs over the guests' worker link as one of the
owner's workers:

- POST /api/workers/enroll mints an owner code (link.OWNER) with the
  dialog's answers and the install line (WORKER_HUB/ENROLL/ACCOUNT/CWD).
- /worker-link/enroll/check says owner: true; /worker-link/enroll makes an
  ordinary owner record (no owner field, id w…, claudeMode own, account),
  and on_paired puts it in the picked profile (default runner if asked).
- Own login only: PATCH refuses the proxy for a linked owner worker
  (the proxy is on the tailnet host; the public host takes no owner token).
- Its login is watched like any own-mode worker's, its link token rotates
  weekly, and the security log records worker_linked.
- sidecar/link.py keeps owner in link.json; install.sh sets such a machine
  up as the owner's (notify shims, no launcher, own-login warning), and
  points systemctl --user at /run/user/<uid> when a shell lacks it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:45:02 +01:00

280 lines
11 KiB
Python

"""
Guest workers — a guest's own machine, paired as a runner.
A worker record with an ``owner`` (a guest's user id) is that guest's: they
paired it from their portal, their composer can run on it, and its sessions
are theirs (``meta.owner``). Everything else about it is an ordinary worker —
the hub pulls runs, ``/feed`` and ``/outbox``; its model calls go through the
Claude proxy.
What changes is trust. The owner's own Macs are trusted with what they send
back; a guest's machine is not. So the hub checks what it would otherwise take
on faith:
* **transcripts** (``may_mirror``): only the sessions the hub itself started
on that computer (``meta.worker``, stamped at spawn) are mirrored, and the
terminal sessions the guest shared (ai-agent Claude, or synced — see
``workers/terminal.py``) — never their other terminal sessions,
and never a session id the meta store places on the lab, another worker or
another person (a hostile ``/feed`` could otherwise overwrite an owner
session's mirror copy, or get its id stamped as the guest's and so read it).
* **outbox items** (``outbox_allowed``): a push, ask, form or ``conv`` patch
must name one of the worker's own sessions — a guest machine never posts
into someone else's conversation, and a push with no session (which would be
the owner's) is refused.
* **model calls**: the proxy token sits on the guest's machine, readable by
the guest — an API key in all but name. Every limit lives in the proxy
(``claudeproxy/limits.py``).
"""
from __future__ import annotations
import datetime
import hmac
import json
import os
import pathlib
import secrets
import threading
import time
def owner_of(w: dict | None) -> str | None:
"""The guest a worker belongs to; None for the owner's own workers."""
return ((w or {}).get("owner") or None)
def is_guest(w: dict | None) -> bool:
return owner_of(w) is not None
def sid_of(rel: str) -> str | None:
"""The session a mirrored transcript belongs to (``<proj>/<sid>.jsonl`` or
a subagent under ``<proj>/<sid>/subagents/``)."""
from .remotefeed import local_rel
parts = local_rel(pathlib.PurePosixPath(rel)).parts
if len(parts) < 2:
return None
return parts[1][:-6] if parts[1].endswith(".jsonl") else parts[1]
def _elsewhere(meta: dict, w: dict) -> bool:
"""The meta places this session on another runner or another person."""
for k in ("workerSource", "worker"):
if meta.get(k) not in (None, "", w["id"]):
return True
return meta.get("owner") not in (None, "", owner_of(w))
def may_mirror(deps, w: dict, rel: str) -> bool:
"""May worker ``w``'s feed write this transcript? Always for the owner's
workers; for a guest's, only a session the hub started there."""
if not is_guest(w):
return True
sid = sid_of(rel)
from . import terminal
return session_belongs(deps, w, sid) and terminal.still_synced(deps, w, sid)
def session_belongs(deps, w: dict, sid: str | None) -> bool:
"""Is ``sid`` a session that runs on worker ``w``?"""
if not sid:
return False
meta = deps.meta_store.peek(str(sid)) or {}
return w["id"] in (meta.get("workerSource"), meta.get("worker")) \
and not _elsewhere(meta, w)
def outbox_allowed(deps, w: dict, kind: str, payload: dict) -> bool:
"""May this outbox item from worker ``w`` be created? A guest worker's
must name one of its own sessions."""
if not is_guest(w):
return True
if kind == "askform":
form = payload.get("form") if isinstance(payload.get("form"), dict) else {}
sid = ((form.get("meta") or {}) if isinstance(form.get("meta"), dict) else {}) \
.get("session")
else:
sid = payload.get("sessionId")
return session_belongs(deps, w, sid)
def stamp(w: dict) -> dict:
"""What every session landing from ``w`` gets besides its worker: a
guest's machine makes the conversation theirs."""
owner = owner_of(w)
return {"owner": owner} if owner else {}
# ── token rotation ───────────────────────────────────────────────────────────
# The previous tokens keep working this long after a rotation: the next probes
# hand the new proxy token over (claudeproxy.maybe_push) and the link token is
# pushed through the link itself.
ROTATE_GRACE_S = 3600
def _iso(ts: float) -> str:
return datetime.datetime.fromtimestamp(ts, datetime.timezone.utc) \
.strftime("%Y-%m-%dT%H:%M:%SZ")
def _epoch(iso: str | None) -> float:
try:
return datetime.datetime.strptime(iso or "", "%Y-%m-%dT%H:%M:%SZ") \
.replace(tzinfo=datetime.timezone.utc).timestamp()
except ValueError:
return 0.0
def prev_valid(w: dict, now: float | None = None) -> bool:
"""Do the previous tokens still work (inside the rotation grace)?"""
return (now or time.time()) < _epoch(w.get("prevTokensUntil"))
def token_matches(w: dict, field: str, token: str) -> bool:
"""``token`` is ``w``'s current ``field`` or — inside the grace — its
previous one."""
cur = w.get(field)
if cur and hmac.compare_digest(cur, token):
return True
prev = w.get(f"{field}Prev")
return bool(prev and prev_valid(w) and hmac.compare_digest(prev, token))
def maybe_rotate(store, w: dict, days: int, now: float | None = None) -> bool:
"""Replace a dialling-out computer's proxy and link tokens once they are
``days`` old (its first probe only dates them) — a guest's, and an
owner's worker on the link too, since its token crosses the internet. The
link token is handed over through the link (``POST /link/token``) before
the hub switches to it; the proxy token goes out with the next proxy push.
True when rotated."""
if w.get("pending") or not w.get("link"):
return False
now = now or time.time()
last = _epoch(w.get("tokensRotatedAt"))
if not last:
store.patch(w["id"], {"tokensRotatedAt": _iso(now)})
return False
if now - last < days * 86400:
return False
from .store import sidecar_request
new_link = secrets.token_urlsafe(32)
sidecar_request(w["url"], w["token"], "/link/token", {"token": new_link}, timeout=15,
label=f"worker {w.get('name') or w['id']}")
store.patch(w["id"], {"linkTokenPrev": w.get("linkToken"), "linkToken": new_link,
"proxyTokenPrev": w.get("proxyToken"),
"proxyToken": secrets.token_urlsafe(32),
"prevTokensUntil": _iso(now + ROTATE_GRACE_S),
"tokensRotatedAt": _iso(now)})
return True
# ── the mirror quota ─────────────────────────────────────────────────────────
class MirrorQuota:
"""Transcript bytes mirrored from each guest computer this month
(``<ledger dir>/mirror-<YYYY-MM>.json``): past the guest's ``mirrorMb``
the mirror stops taking its files until the 1st."""
def __init__(self, root: pathlib.Path | None = None):
from claudeproxy.limits import LEDGER_DIR
self.root = pathlib.Path(root or LEDGER_DIR)
self._lock = threading.Lock()
self._month = ""
self._bytes: dict[str, int] = {}
self._dirty = 0.0
def _path(self, month: str) -> pathlib.Path:
return self.root / f"mirror-{month}.json"
def _roll(self) -> None:
month = time.strftime("%Y-%m", time.gmtime())
if month != self._month:
self._month = month
try:
self._bytes = json.loads(self._path(month).read_text()) or {}
except (OSError, ValueError):
self._bytes = {}
def add(self, wid: str, n: int) -> None:
with self._lock:
self._roll()
self._bytes[wid] = self._bytes.get(wid, 0) + max(0, int(n))
if time.time() - self._dirty > 30:
self._dirty = time.time()
self.root.mkdir(parents=True, exist_ok=True)
tmp = self._path(self._month).with_suffix(".tmp")
tmp.write_text(json.dumps(self._bytes))
os.replace(tmp, self._path(self._month))
def used(self, wid: str) -> int:
with self._lock:
self._roll()
return self._bytes.get(wid, 0)
MIRROR = MirrorQuota()
def mirror_ok(deps, w: dict) -> bool:
if not is_guest(w):
return True
mb = deps.users.defaults()["computerLimits"]["mirrorMb"]
return MIRROR.used(w["id"]) < mb * 1024 * 1024
# ── bad tokens from one address ──────────────────────────────────────────────
class BadTokens:
"""Addresses that keep presenting tokens nobody holds (``/proxy``,
``/worker-link``): past ``LIMIT`` in ``WINDOW_S`` they are refused for
``LOCK_S`` before any token is even looked at."""
LIMIT, WINDOW_S, LOCK_S = 20, 600, 3600
def __init__(self):
self._lock = threading.Lock()
self._fails: dict[str, list[float]] = {}
self._locked: dict[str, float] = {}
def locked(self, ip: str) -> bool:
with self._lock:
until = self._locked.get(ip, 0)
if until and until < time.time():
self._locked.pop(ip, None)
return False
return bool(until)
def fail(self, ip: str) -> bool:
"""Count one; True when this one locks the address."""
if not ip:
return False
now = time.time()
with self._lock:
hits = [t for t in self._fails.get(ip, []) if now - t < self.WINDOW_S]
hits.append(now)
self._fails[ip] = hits
if len(hits) >= self.LIMIT and ip not in self._locked:
self._locked[ip] = now + self.LOCK_S
self._fails.pop(ip, None)
return True
return False
BAD = BadTokens()
def bad_token(deps, request, where: str) -> None:
"""Count a refused token from this request's address; lock it (and log it)
once there are too many."""
from security.service import client_ip, record
ip = client_ip(request)
if BAD.fail(ip):
record(deps, "ip_locked", detail=f"{ip}: {BadTokens.LIMIT} bad tokens on {where} "
f"in {BadTokens.WINDOW_S // 60} min — refused "
f"for {BadTokens.LOCK_S // 60} min",
request=request)
def ip_locked(request) -> bool:
from security.service import client_ip
return BAD.locked(client_ip(request))