Files
gabrielvidalandClaude Opus 5.5 7ecdc46c7e fix(claudeproxy): a stale worker record never mints a second proxy token
A probe handed one stale record to the Claude and the opencode pushes in
turn: both minted, the worker got the first token and the hub kept the
second — the new computer's first calls 401'd until the next probe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:36:49 +01:00

343 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
The Claude proxy — a worker's Claude Code bills the hub's logins.
A paired worker ran Claude Code on a login of its own (its Keychain login,
matched against the hub's accounts at pairing). It still can — the worker's
``claudeMode`` is ``own`` — but by default the logins live on the lab only
(each account a config dir there, signed in from Settings → Accounts) and the
hub is an Anthropic API proxy in front of them (``claudeMode: proxy``):
* **which accounts** a proxied worker may bill is its record's
``claudeAccounts`` (Settings → Profiles → the worker: a checkbox per Claude
account; its profile entry's ★ among them is what a new prompt there bills,
and what a terminal ``claude`` on the machine uses).
* **how the worker gets there**: each liveness probe compares ``/health``'s
``claudeProxy.hash`` with what the hub would send — the proxy ``url``
(``CLAUDE_PROXY_URL``), the worker's own ``proxyToken`` (minted here, on its
record, never served), the accounts and the machine default — and POSTs
``/claude-proxy`` when they differ. The worker launches a run on one of
those accounts with ``ANTHROPIC_BASE_URL=<url>/<account>`` and its token as
``CLAUDE_CODE_OAUTH_TOKEN``, and writes the default account's pair into its
``~/.claude/settings.json`` for terminal sessions (``sidecar/claude_proxy.py``).
* **the swap** (``routes.py``): a request on ``/proxy/claude/<account>/v1/…``
names its worker by that token; the account must be one of the worker's;
the token is replaced by the account's real OAuth access token — read
through the host sidecar (``GET /accounts/{id}/access-token``, cached here a
few minutes; the CLI does every refresh) — and the reply streams back. Its
rate-limit headers are the account's live plan usage (``usage/poller``).
The direction of everything else is unchanged (the hub pulls runs, feeds and
the outbox); model calls are the one thing a worker sends the hub, and its
token can do nothing but that, for its own accounts.
"""
from __future__ import annotations
import hashlib
import hmac
import json
import os
import secrets
import threading
import time
from fastapi import HTTPException
import accounts as accounts_mod
from core.config import SIDECAR_TOKEN, SIDECAR_URL
# Where a worker reaches the proxy: through Traefik, on the admin host (a
# router of its own that skips Authelia for this path — the bearer is the
# auth). The tailnet's DNS resolves *.lab to the lab, so every worker can.
PROXY_URL = (os.environ.get("CLAUDE_PROXY_URL") or os.environ.get(
"AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/") + "/proxy/claude").rstrip("/")
# A guest's computer is on no network of ours: it reaches the proxy on the
# public guest host, where only guest computers' tokens are taken (routes.py).
GUEST_PROXY_URL = (os.environ.get("GUEST_CLAUDE_PROXY_URL") or (
os.environ.get("GUEST_PUBLIC_URL", "").rstrip("/") + "/proxy/claude")).rstrip("/")
UPSTREAM = os.environ.get("CLAUDE_PROXY_UPSTREAM", "https://api.anthropic.com").rstrip("/")
# A token read from the lab is reused this long at most (the CLI may refresh
# it meanwhile), and never past its own expiry minus the margin.
TOKEN_TTL_S = float(os.environ.get("CLAUDE_PROXY_TOKEN_TTL_S", "300"))
TOKEN_MARGIN_S = 60
# Between two pushes of the same config to one worker.
RETRY_S = 60
CURRENT, OUTDATED, FAILED, UNSUPPORTED, OFF = (
"current", "outdated", "failed", "unsupported", "off")
# ── which accounts, which token ──────────────────────────────────────────────
OWN, PROXY = "own", "proxy"
def mode(w: dict | None) -> str:
"""``proxy`` (bills the hub's logins) or ``own`` (its machine's login). A
record from before the proxy ran on its own login, and keeps doing so
until the switch on its page moves it."""
if (w or {}).get("owner"):
return PROXY
m = (w or {}).get("claudeMode")
return m if m in (OWN, PROXY) else OWN
def claude_accounts(w: dict | None) -> list[str]:
"""The Claude accounts a worker can run on: its own login's account, or —
proxied — the hub's accounts ticked for it (none ticked yet: the one its
own login was, else the default account)."""
w = w or {}
if w.get("owner"):
# A guest's computer bills the owner's default account, nothing else
# (users/computers.py) — whatever its record says.
return [accounts_mod.DEFAULT]
if mode(w) == OWN:
a = accounts_mod.valid_for(w.get("account"), "claude")
return [a] if a else []
raw = w.get("claudeAccounts")
if raw is None:
raw = [w.get("account") or accounts_mod.DEFAULT]
return clean_accounts(raw)
def proxied_accounts(w: dict | None) -> list[str]:
return claude_accounts(w) if mode(w) == PROXY else []
def clean_accounts(raw) -> list[str]:
"""A ``claudeAccounts`` edit: known Claude accounts, in catalog order."""
want = {accounts_mod.valid_for(a, "claude") for a in (raw or [])}
return [a for a in accounts_mod.for_harness("claude") if a in want]
def terminal_account(store, w: dict) -> str | None:
"""The account a session started on the machine itself bills: its own
login's, or — proxied — its ★ (the profile entry's default login)."""
if mode(w) == OWN:
return w.get("account")
held = proxied_accounts(w)
star_of = getattr(store, "star_of", None)
star = star_of(w["id"], held) if star_of else None
return star if star in held else (held[0] if held else None)
_mint_lock = threading.Lock()
def ensure_token(store, w: dict) -> dict:
"""The worker's proxy bearer, minted on first need. Re-read first: a
probe hands one stale record to the Claude and the opencode pushes in
turn, and minting twice sent the worker a token the hub had already
replaced (its first calls then 401'd until the next probe)."""
if w.get("proxyToken"):
return w
with _mint_lock:
cur = store.get(w["id"]) or w
if cur.get("proxyToken"):
return cur
return store.patch(w["id"], {"proxyToken": secrets.token_urlsafe(32)}) or cur
def worker_for_token(store, token: str) -> dict | None:
"""The worker holding this proxy token — a guest computer's previous one
too, for the hour after a rotation (workers/guests.maybe_rotate)."""
from workers import guests
if not token:
return None
for w in store.list():
if guests.token_matches(w, "proxyToken", token):
return w
return None
def fingerprint(url: str, token: str, accts: list[str], default: str | None = None) -> str:
"""Identical to ``sidecar/claude_proxy.fingerprint`` — the worker shows
it in ``/health``, the hub computes it from what it would send."""
raw = json.dumps([url, hashlib.sha256(token.encode()).hexdigest(), sorted(accts),
default or ""])
return hashlib.sha256(raw.encode()).hexdigest()[:16]
def desired(store, w: dict) -> dict:
"""What the worker should hold. Its own login: nothing (an empty list
makes the sidecar drop the config and the settings.json default)."""
accts = proxied_accounts(w)
if w.get("owner"):
# A guest's machine: the public guest host, and nothing written into
# its own ~/.claude/settings.json — its terminal `claude` stays theirs.
return {"url": GUEST_PROXY_URL, "token": w.get("proxyToken") or "",
"accounts": accts, "default": None}
return {"url": PROXY_URL, "token": w.get("proxyToken") or "", "accounts": accts,
"default": terminal_account(store, w) if accts else None}
def _hash(d: dict) -> str:
return fingerprint(d["url"], d["token"], d["accounts"], d.get("default"))
def status(store, w: dict, st: dict) -> str:
"""Where the worker's copy stands: ``current``, ``outdated`` (the next
probe pushes it), ``failed``, ``unsupported`` (a sidecar from before the
proxy — its next update brings it), ``off`` (it runs on its own login)."""
held = st.get("claudeProxy")
if not proxied_accounts(w):
return OFF if not (held or {}).get("accounts") else OUTDATED
if held is None:
return UNSUPPORTED
d = desired(store, w)
if d["token"] and held.get("hash") == _hash(d):
return CURRENT
return FAILED if st.get("claudeProxyError") else OUTDATED
_attempts: dict[str, tuple[str, float]] = {}
def push(store, w: dict) -> dict:
"""Send the worker its proxy config now (an empty account list — its own
login — drops it there)."""
from workers.store import sidecar_request
w = ensure_token(store, w)
d = desired(store, w)
try:
if d["accounts"]:
out = sidecar_request(w["url"], w["token"], "/claude-proxy", d, timeout=10,
label=f"worker {w.get('name') or w['id']}")
else:
out = sidecar_request(w["url"], w["token"], "/claude-proxy", None,
method="DELETE", timeout=10,
label=f"worker {w.get('name') or w['id']}")
except HTTPException as e:
msg = e.detail.get("message") if isinstance(e.detail, dict) else str(e.detail)
store.set_status(w["id"], claudeProxyError=(msg or "push failed")[:200])
raise
store.set_status(w["id"], claudeProxy=out.get("claudeProxy"), claudeProxyError=None)
return out
def maybe_push(store, w: dict) -> bool:
"""After each probe: True when a config was sent. The same config is
retried after ``RETRY_S``."""
if not store.online(w["id"]):
return False
w = ensure_token(store, w)
if status(store, w, store.status(w["id"])) not in (OUTDATED, FAILED):
return False
h = _hash(desired(store, w))
last = _attempts.get(w["id"])
if last and last[0] == h and time.time() - last[1] < RETRY_S:
return False
_attempts[w["id"]] = (h, time.time())
try:
push(store, w)
except HTTPException:
return False
return True
def public(store, w: dict, st: dict) -> dict:
"""What the worker's page shows (never the token)."""
held = st.get("claudeProxy")
return {"mode": mode(w), "accounts": proxied_accounts(w),
"default": terminal_account(store, w) if proxied_accounts(w) else None,
"status": status(store, w, st),
"held": (held or {}).get("accounts") if held else None,
"settingsDefault": (held or {}).get("settings") if held else None,
"error": st.get("claudeProxyError"), "lastUsedAt": st.get("proxyLastAt")}
# ── live plan usage off the replies ──────────────────────────────────────────
# `anthropic-ratelimit-unified-<window>-utilization` (0–1) and `…-reset`
# (epoch s): the same figures Claude Code's /usage and status line show.
_WINDOWS = {"5h": "five_hour", "7d": "seven_day"}
_RL = "anthropic-ratelimit-unified-"
def usage_from_headers(headers, now: float | None = None) -> dict | None:
"""A reply's rate-limit headers → a usage snapshot (``usage/poller``'s
``{updatedAt, windows: {name: {pct, resetsAt}}}``), None without any."""
windows: dict[str, dict] = {}
for k, v in headers.items():
k = k.lower()
if not (k.startswith(_RL) and k.endswith("-utilization")):
continue
key = k[len(_RL):-len("-utilization")]
name = _WINDOWS.get(key) or (f"seven_day_{key[3:]}" if key.startswith("7d_") else None)
try:
pct = round(float(v) * 100, 2)
except ValueError:
continue
if not name:
continue
reset = headers.get(f"{_RL}{key}-reset")
try:
reset = int(float(reset)) if reset is not None else None
except ValueError:
reset = None
windows[name] = {"pct": pct, "resetsAt": reset}
if not windows:
return None
return {"updatedAt": now if now is not None else time.time(), "windows": windows}
# ── the lab's access tokens ──────────────────────────────────────────────────
class TokenCache:
"""Each account's OAuth access token, as the host sidecar reads it from
the account's ``.credentials.json`` (refreshing it through the CLI when it
is about to expire). One fetch at a time per account."""
def __init__(self, fetch=None):
self._fetch = fetch or _fetch_token
self._tokens: dict[str, tuple[str, float, float]] = {}
self._extra: dict[str, dict] = {}
self._locks: dict[str, threading.Lock] = {}
self._guard = threading.Lock()
def _lock(self, account: str) -> threading.Lock:
with self._guard:
return self._locks.setdefault(account, threading.Lock())
def get(self, account: str, *, refused: str | None = None) -> str:
"""The account's token. ``refused`` = the one upstream just turned
down: fetch again, asking the lab to refresh unless it already has."""
with self._lock(account):
hit = self._tokens.get(account)
now = time.time()
if hit and hit[0] != refused and now - hit[2] < TOKEN_TTL_S \
and (not hit[1] or hit[1] - now > TOKEN_MARGIN_S):
return hit[0]
out = self._fetch(account, refresh=bool(refused) and (not hit or hit[0] == refused))
tok = out.get("accessToken") or ""
if not tok:
raise HTTPException(409, {"message": f"no {account} login on the Homelab",
"kind": "auth", "account": account})
exp = out.get("expiresAt")
self._tokens[account] = (tok, exp / 1000 if isinstance(exp, (int, float)) else 0.0,
now)
self._extra[account] = {k: v for k, v in out.items() if k != "accessToken"}
return tok
def extra(self, account: str) -> dict:
"""What came with the account's token besides it (opencode's ChatGPT
``accountId``)."""
return self._extra.get(account) or {}
def forget(self, account: str | None = None) -> None:
with self._guard:
if account:
self._tokens.pop(account, None)
else:
self._tokens.clear()
def _fetch_token(account: str, refresh: bool = False) -> dict:
from workers.store import sidecar_request
if not SIDECAR_TOKEN:
raise HTTPException(503, {"message": "sidecar not configured", "kind": "sidecar"})
path = f"/accounts/{account}/access-token" + ("?refresh=1" if refresh else "")
# A stale token is refreshed by a one-turn CLI call first: allow for it.
return sidecar_request(SIDECAR_URL, SIDECAR_TOKEN, path, None, method="GET",
timeout=120)
TOKENS = TokenCache()