Files

562 lines
24 KiB
Python

"""
The worker link — a worker that dials out, for a machine the hub can't reach.
A tailnet worker listens on its Tailscale address and the hub calls it. A
guest's computer is on no network of ours, so it calls us instead: it
long-polls the guest host over HTTPS and answers whatever the hub asks. So
does an owner's machine the hub can't reach either (since 2026-11-19 — an
Orus devbox, only on the company's tailnet): Settings → Profiles → *Pair a
worker* → *It dials out* mints an **owner code** (``OWNER``, with the
dialog's answers in ``opts``) for ``POST /api/workers/enroll``, and the
record it makes is an ordinary owner worker (no ``owner`` field) that joins
the picked profile once paired, on its own Claude login — the public host
takes no owner proxy token. Nothing upstream changes — the record's ``url`` is this backend's own
``/_tunnel/<id>`` (loopback only), every existing caller (the monitor, the
feed and outbox mirrors, spawn/resume, uploads, lab sync, the proxy push)
does its usual HTTP request there, and this module relays it.
* ``POST /worker-link/enroll {code, pairCode, hostname, …}`` — the installer
trades the one-time **enroll code** the guest got from their portal (Me →
*My computers* → *Add*, ``ENROLL_TTL_S``) for a **link token**, and hands
over the sidecar's own pairing code. The hub mints the record (its id is the
hub's, never the machine's: a guest must not be able to name an owner
worker's id), ``pending`` until the pairing below. Every code the portal
showed stays good for its hour (up to ``ENROLL_LIVE_MAX`` per guest): a
second *Add* must not kill the line already pasted in a terminal. The
first one used retires the rest.
* ``POST /worker-link/enroll/check {code}`` — the installer asks, before its
minutes-long build, whether the code would be taken (it isn't consumed).
* ``POST /worker-link/poll`` (Bearer link token) — waits ≤ ``POLL_WAIT_S``
for requests, answers up to ``POLL_BATCH`` at once. A body up to
``INLINE_MAX`` rides inline (base64); a bigger one is fetched from
``GET /worker-link/body/<rid>``.
* ``POST /worker-link/reply/<rid>`` — the raw reply body, its status in
``x-link-status`` and its headers (JSON) in ``x-link-headers``.
* The first poll of a pending record runs the ordinary pairing through the
link (``POST /pair`` with the code the installer handed over): the sidecar
mints the bearer the hub then sends with every request, exactly as on the
tailnet.
A worker counts as connected while a poll is parked here or ended less than
``LINKED_S`` ago; otherwise a call fails at once with 502 ``worker_offline``,
which the monitor reads as offline.
Long-poll rather than a WebSocket: each exchange is a plain HTTPS request
that raspy2's passthrough and Traefik (``readTimeout: 600s``) carry as-is,
and the worker needs nothing beyond the standard library.
"""
from __future__ import annotations
import asyncio
import base64
import datetime
import hashlib
import json
import os
import pathlib
import secrets
import threading
import time
import uuid
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel
from . import guests
POLL_WAIT_S = float(os.environ.get("WORKER_LINK_POLL_WAIT_S", "25"))
POLL_BATCH = 8
LINKED_S = 40.0
CALL_TIMEOUT_S = 180.0
INLINE_MAX = 512 * 1024
REPLY_MAX = 64 * 1024 * 1024
ENROLL_TTL_S = int(os.environ.get("WORKER_ENROLL_TTL_S", str(3600)))
ENROLL_LIVE_MAX = 5
# Where this backend reaches itself (the tunnelled workers' ``url``).
SELF_URL = os.environ.get("WORKER_LINK_SELF_URL", "http://127.0.0.1:8080").rstrip("/")
ENROLL_PATH = os.environ.get("WORKER_ENROLL_PATH", "/data/worker-enroll.json")
# Never relayed either way: hop-by-hop, and what the HTTP stack sets itself.
_HOP = {"host", "connection", "keep-alive", "transfer-encoding", "te", "trailer",
"upgrade", "content-length", "proxy-authorization", "accept-encoding",
"content-encoding"}
# Who an owner's code is for (``EnrollCodes`` keys codes by user id; no
# guest id starts with ``@``).
OWNER = "@owner"
def tunnel_url(wid: str) -> str:
return f"{SELF_URL}/_tunnel/{wid}"
def is_linked_record(w: dict | None) -> bool:
return bool((w or {}).get("link"))
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _hash(code: str) -> str:
return hashlib.sha256(code.strip().upper().encode()).hexdigest()
# ── enroll codes ─────────────────────────────────────────────────────────────
class EnrollCodes:
"""One-time codes a guest's portal hands out (hashed on disk, 0600) —
and the owner's *Pair a worker* → *It dials out* (user ``OWNER``, the
dialog's answers in ``opts``)."""
def __init__(self, path: str = ENROLL_PATH):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
def _load(self) -> dict:
try:
data = json.loads(self.path.read_text(encoding="utf-8")) or {}
except (OSError, ValueError):
return {}
now = time.time()
return {h: r for h, r in data.items() if float(r.get("expires") or 0) > now}
def _save(self, data: dict) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f)
os.replace(tmp, self.path)
def mint(self, uid: str, opts: dict | None = None) -> dict:
# No 0/O/1/I/L: read off one screen, maybe typed on another.
code = "".join(secrets.choice("ABCDEFGHJKMNPQRSTUVWXYZ23456789") for _ in range(16))
expires = time.time() + ENROLL_TTL_S
with self._lock:
data = self._load()
# The guest's older codes stay good — only the oldest beyond the
# cap go (2026-11-03: a re-opened dialog revoked the line Akira
# had already pasted, and the install failed at its very end).
mine = sorted((float(r.get("expires") or 0), h) for h, r in data.items()
if r.get("user") == uid)
for _, h in mine[:max(0, len(mine) - ENROLL_LIVE_MAX + 1)]:
data.pop(h)
data[_hash(code)] = {"user": uid, "expires": expires, **({"opts": opts} if opts else {})}
self._save(data)
return {"code": code, "expiresAt": int(expires)}
def peek(self, code: str) -> dict | None:
"""``{user, expires}`` for a live code, without consuming it."""
with self._lock:
return self._load().get(_hash(code or ""))
def take(self, code: str) -> str | None:
"""The guest a code was minted for, consuming it and retiring the
guest's other codes (that *Add* is done); None if unknown or expired."""
h = _hash(code or "")
with self._lock:
data = self._load()
rec = data.pop(h, None)
if rec:
data = {k: r for k, r in data.items() if r.get("user") != rec.get("user")}
self._save(data)
return rec.get("user") if rec else None
def pending(self, uid: str) -> bool:
with self._lock:
return any(r.get("user") == uid for r in self._load().values())
# ── the relay ────────────────────────────────────────────────────────────────
class _Call:
__slots__ = ("rid", "wid", "method", "path", "headers", "body", "future")
def __init__(self, wid: str, method: str, path: str, headers: dict, body: bytes):
self.rid = uuid.uuid4().hex
self.wid, self.method, self.path = wid, method, path
self.headers, self.body = headers, body
self.future: asyncio.Future = asyncio.get_running_loop().create_future()
class LinkHub:
"""The requests waiting for each worker's next poll, and the replies they
wait for. Lives on the event loop: every method is called from it."""
def __init__(self):
self._queues: dict[str, asyncio.Queue] = {}
self._calls: dict[str, _Call] = {}
self._polling: dict[str, int] = {}
self._last: dict[str, float] = {}
def _q(self, wid: str) -> asyncio.Queue:
q = self._queues.get(wid)
if q is None:
q = self._queues[wid] = asyncio.Queue()
return q
def linked(self, wid: str) -> bool:
return self._polling.get(wid, 0) > 0 or time.time() - self._last.get(wid, 0) < LINKED_S
def last_poll(self, wid: str) -> float | None:
return self._last.get(wid)
async def call(self, wid: str, method: str, path: str, headers: dict, body: bytes,
timeout: float = CALL_TIMEOUT_S) -> tuple[int, dict, bytes]:
if not self.linked(wid):
return 502, {"content-type": "application/json"}, json.dumps({"detail": {
"message": "the computer is not connected", "kind": "worker_offline"}}).encode()
c = _Call(wid, method, path, headers, body)
self._calls[c.rid] = c
self._q(wid).put_nowait(c)
try:
return await asyncio.wait_for(c.future, timeout)
except asyncio.TimeoutError:
return 504, {"content-type": "application/json"}, json.dumps({"detail": {
"message": "the computer didn't answer in time", "kind": "worker_offline"}}).encode()
finally:
self._calls.pop(c.rid, None)
async def poll(self, wid: str, wait: float = POLL_WAIT_S) -> list[dict]:
q = self._q(wid)
self._polling[wid] = self._polling.get(wid, 0) + 1
try:
try:
first = await asyncio.wait_for(q.get(), wait)
except asyncio.TimeoutError:
return []
batch = [first]
while len(batch) < POLL_BATCH and not q.empty():
batch.append(q.get_nowait())
return [self._wire(c) for c in batch if not c.future.done()]
finally:
self._polling[wid] -= 1
self._last[wid] = time.time()
@staticmethod
def _wire(c: _Call) -> dict:
out = {"id": c.rid, "method": c.method, "path": c.path, "headers": c.headers}
if c.body:
if len(c.body) <= INLINE_MAX:
out["body"] = base64.b64encode(c.body).decode()
else:
out["bodyUrl"] = f"/worker-link/body/{c.rid}"
out["bodySize"] = len(c.body)
return out
def body(self, wid: str, rid: str) -> bytes | None:
c = self._calls.get(rid)
return c.body if c and c.wid == wid else None
def reply(self, wid: str, rid: str, status: int, headers: dict, body: bytes) -> bool:
c = self._calls.get(rid)
if not c or c.wid != wid or c.future.done():
return False
c.future.set_result((status, headers, body))
return True
def forget(self, wid: str) -> None:
"""An unpaired worker: fail what waits for it."""
for c in [c for c in self._calls.values() if c.wid == wid]:
if not c.future.done():
c.future.set_result((502, {}, b'{"detail":{"message":"unpaired",'
b'"kind":"worker_offline"}}'))
self._queues.pop(wid, None)
self._last.pop(wid, None)
HUB = LinkHub()
ENROLL = EnrollCodes()
# ── who is polling ───────────────────────────────────────────────────────────
def mint_link_token() -> str:
return secrets.token_urlsafe(32)
def worker_for_link_token(store, token: str) -> dict | None:
if not token:
return None
lookup = getattr(store, "by_link_token", None)
if lookup is not None:
return lookup(token)
for w in store.list():
if guests.token_matches(w, "linkToken", token):
return w
return None
def _bearer(request: Request) -> str:
auth = request.headers.get("authorization") or ""
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
def _err(status: int, message: str, kind: str) -> JSONResponse:
return JSONResponse({"detail": {"message": message, "kind": kind}}, status_code=status)
def _from_loopback(request: Request) -> bool:
"""``/_tunnel`` is this backend talking to itself: the client is the
container's own loopback, and nothing came through Traefik."""
host = request.client.host if request.client else ""
return host in ("127.0.0.1", "::1") and "x-forwarded-for" not in request.headers \
and "x-real-ip" not in request.headers
# ── pairing through the link ─────────────────────────────────────────────────
_pairing: set[str] = set()
def complete_pairing(deps, wid: str) -> None:
"""The pending record's first poll arrived: run ``/pair`` through the
link with the code the installer handed over (in a thread — the call
comes back through this very backend)."""
from .store import sidecar_request
try:
w = deps.worker_store.get(wid)
if not w or not w.get("pending") or not w.get("pairCode"):
return
out = sidecar_request(w["url"], "", "/pair", {"code": w["pairCode"],
"hubName": "ai-agent"},
timeout=60, label=f"worker {w.get('name') or wid}")
if not out.get("token"):
raise RuntimeError("the computer answered /pair without a token")
deps.worker_store.patch(wid, {
"token": out["token"], "pending": False, "pairCode": None,
"hostname": out.get("hostname") or w.get("hostname"),
"platform": out.get("platform") or w.get("platform"),
"machine": out.get("machine") or w.get("machine"),
"version": out.get("version"), "cwd": out.get("cwd"),
"permissionMode": out.get("permissionMode"), "pairedAt": _now_iso()})
deps.worker_store.set_status(wid, status="online", lastSeen=_now_iso(),
lastError=None)
on_paired(deps, deps.worker_store.get(wid) or w)
except Exception as e:
deps.worker_store.set_status(wid, lastError=f"pairing: {e}"[:200])
finally:
_pairing.discard(wid)
def on_paired(deps, w: dict) -> None:
"""A guest's computer is in: tell the owner (and the guest's open pages).
An owner's machine that dials out joins the profile its dialog picked."""
deps.hub.publish({"type": "workers"})
owner = guests.owner_of(w)
from security.service import record
if not owner:
profile = w.get("enrollProfile")
if profile and not deps.profile_store.get(profile):
profile = None
deps.profile_store.assign_worker(w, profile)
if w.get("enrollDefault"):
deps.profile_store.patch_runner(w["id"], {"default": True})
deps.worker_store.patch(w["id"], {"enrollProfile": None, "enrollDefault": None})
deps.hub.publish({"type": "profiles"})
record(deps, "worker_linked",
detail=f"{w.get('name')} ({w.get('hostname')}, {w.get('platform')})",
data={"worker": w["id"]})
return
record(deps, "guest_worker_paired", who=owner,
detail=f"{w.get('name')} ({w.get('hostname')}, {w.get('platform')})",
data={"worker": w["id"]})
try:
from notifications.service import _create_notify
u = deps.users.get(owner) or {}
_create_notify(deps, {
"title": f"🖥️ {u.get('name') or owner} added a computer",
"message": f"{w.get('name') or w.get('hostname')} ({w.get('platform') or '?'}) — "
"its Claude calls bill your account, within their limits",
"type": "service", "url": f"/settings/users/{owner}?tab=access"})
except Exception:
pass
# ── routes ───────────────────────────────────────────────────────────────────
router = APIRouter()
class EnrollBody(BaseModel):
code: str
pairCode: str
hostname: str | None = None
name: str | None = None
platform: str | None = None
machine: str | None = None
class CheckBody(BaseModel):
code: str
def _vet(request: Request, code: str) -> tuple[dict | None, JSONResponse | None]:
"""The live code's record if it would enroll now, else the refusal."""
deps = request.app.state.ai
if guests.ip_locked(request):
return None, _err(429, "too many bad codes from this address — try again in an "
"hour", "ip_locked")
rec = ENROLL.peek(code)
if not rec or not (_owners(rec) or deps.users.active(rec.get("user"))):
guests.bad_token(deps, request, "/worker-link/enroll")
return None, _err(403, "this code is unknown, already used or over an hour old — "
"get a new one from your portal (Settings → My computers)",
"enroll_code")
if _owners(rec):
return rec, None
from users.computers import may_add
problem = may_add(deps, rec["user"])
if problem:
return None, _err(403, problem, "enroll_refused")
return rec, None
def _owners(rec: dict | None) -> bool:
"""A code the owner's *Pair a worker* minted (not a guest's portal)."""
return (rec or {}).get("user") == OWNER
@router.post("/worker-link/enroll/check", include_in_schema=False)
def enroll_check(request: Request, body: CheckBody):
"""Would this code enroll? The installer asks before its minutes-long
build, so a dead code fails in a second; the code stays unused. An
owner's code says so — the installer then sets the machine up as one of
the owner's workers (its own login, `notify` in a terminal), not as a
guest's computer."""
rec, err = _vet(request, body.code)
if err:
return err
out = {"ok": True, "expiresAt": int(float(rec["expires"]))}
if _owners(rec):
out.update(owner=True, account=(rec.get("opts") or {}).get("account"))
return out
# One enroll at a time between taking a code and recording its computer: the
# count ``may_add`` reads must include the enroll that just finished.
_ENROLL_LOCK = threading.Lock()
@router.post("/worker-link/enroll", include_in_schema=False)
def enroll(request: Request, body: EnrollBody):
"""The installer trades the portal's one-time code for a link token."""
deps = request.app.state.ai
rec, err = _vet(request, body.code)
if err:
return err
from users.computers import may_add
host = (body.hostname or "").strip()[:60] or "computer"
common = {
"link": True, "pending": True, "hostname": host,
"platform": (body.platform or "")[:20] or None,
"machine": (body.machine or "")[:20] or None,
"token": None, "linkToken": mint_link_token(),
"pairCode": (body.pairCode or "").strip().upper()[:32],
"autoRoute": False, "enrolledAt": _now_iso()}
with _ENROLL_LOCK:
uid = ENROLL.take(body.code)
if not uid: # taken by a concurrent enroll since the check above
return _err(403, "this code was just used", "enroll_code")
if uid == OWNER:
# One of the owner's workers, on its own Claude login: the proxy
# is on the tailnet host, which this machine can't reach.
opts = rec.get("opts") or {}
wid = "w" + uuid.uuid4().hex[:11]
deps.worker_store.put({
**common, "id": wid, "url": tunnel_url(wid),
"name": (opts.get("name") or body.name or "").strip()[:60] or host,
"account": opts.get("account"), "claudeMode": "own",
"enrollProfile": opts.get("profile") or None,
"enrollDefault": bool(opts.get("default"))})
else:
# Counted again with the code in hand and the lock held: the check
# above saw the count before a concurrent enroll added its computer.
problem = may_add(deps, uid)
if problem:
return _err(403, problem, "enroll_refused")
wid = "g" + uuid.uuid4().hex[:11]
deps.worker_store.put({
**common, "id": wid, "owner": uid, "url": tunnel_url(wid),
"name": (body.name or "").strip()[:60] or host, "claudeMode": "proxy"})
w = deps.worker_store.get(wid) or {}
deps.hub.publish({"type": "workers"})
return {"workerId": wid, "linkToken": w.get("linkToken"), "name": w.get("name"),
**({"owner": True} if uid == OWNER else {})}
def _linked_worker(request: Request):
if guests.ip_locked(request):
return None, _err(429, "too many bad tokens from this address — try again "
"in an hour", "ip_locked")
w = worker_for_link_token(request.app.state.ai.worker_store, _bearer(request))
if not w or not is_linked_record(w):
guests.bad_token(request.app.state.ai, request, "/worker-link")
return None, _err(401, "unknown link token — this computer was removed; "
"add it again from your portal", "link_token")
owner = guests.owner_of(w)
deps = request.app.state.ai
if owner and (not deps.users.active(owner) or deps.security_state.guests_locked()):
return None, _err(403, "guest access is paused", "guests_locked")
return w, None
@router.post("/worker-link/poll", include_in_schema=False)
async def poll(request: Request):
w, err = _linked_worker(request)
if err:
return err
deps = request.app.state.ai
if w.get("pending") and w["id"] not in _pairing:
_pairing.add(w["id"])
asyncio.get_running_loop().run_in_executor(None, complete_pairing, deps, w["id"])
reqs = await HUB.poll(w["id"])
return {"requests": reqs}
@router.get("/worker-link/body/{rid}", include_in_schema=False)
def body(request: Request, rid: str):
w, err = _linked_worker(request)
if err:
return err
data = HUB.body(w["id"], rid)
if data is None:
return _err(404, "no such request", "link_request")
return Response(data, media_type="application/octet-stream")
@router.post("/worker-link/reply/{rid}", include_in_schema=False)
async def reply(request: Request, rid: str):
w, err = _linked_worker(request)
if err:
return err
try:
status = int(request.headers.get("x-link-status") or "502")
headers = json.loads(request.headers.get("x-link-headers") or "{}")
except ValueError:
return _err(400, "bad reply headers", "link_reply")
if not isinstance(headers, dict):
headers = {}
data = await request.body()
if len(data) > REPLY_MAX:
return _err(413, "reply too large", "link_reply")
headers = {str(k).lower(): str(v) for k, v in headers.items()
if str(k).lower() not in _HOP}
HUB.reply(w["id"], rid, status, headers, data)
return {"ok": True}
@router.api_route("/_tunnel/{wid}/{path:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE"], include_in_schema=False)
async def tunnel(request: Request, wid: str, path: str):
if not _from_loopback(request):
return _err(404, "not found", "not_found")
w = request.app.state.ai.worker_store.get(wid)
if not w or not is_linked_record(w):
return _err(404, "unknown worker", "worker_unknown")
qs = request.url.query
headers = {k.lower(): v for k, v in request.headers.items() if k.lower() not in _HOP}
status, rheaders, data = await HUB.call(wid, request.method,
"/" + path + (f"?{qs}" if qs else ""),
headers, await request.body())
media = rheaders.pop("content-type", None)
return Response(data, status_code=status, headers=rheaders, media_type=media)