Split the internet upgrades: API-only tunnel, OIDC, authenticator codes, expose-dashboard
install-newt now sets up the tunnel for the API only; the dashboard stays on the LAN. Dashboard sign-in is its own step: install-oidc (the OIDC flow, split out) or install-otp, which pairs authenticator apps with a QR code in the terminal (stdlib QR encoder, TOTP per RFC 6238) so a code also opens the dashboard, with replay and lockout rules. expose-dashboard walks through publishing the dashboard, only after install-newt, and warns while it's protected by the API key alone; with codes it offers to switch the key off for the dashboard. Each install-* has a remove-*. Also opencode-install.sh: a standalone script, fetched from the repo, that installs opencode if needed, saves the API key to a 0600 file and adds the provider to opencode.json for new and existing configs. /v1/models reports whether the model reasons, for that script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e6ff4ce909
commit
c8b70afdbf
20 changed files with 1715 additions and 239 deletions
|
|
@ -1,7 +1,10 @@
|
|||
"""Dashboard: status, metrics and model switching. Stdlib only.
|
||||
|
||||
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or,
|
||||
when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py).
|
||||
Serves index.html and a JSON API on cfg["web_port"]. Who gets in:
|
||||
- by default, the API key (sent as a Bearer header by the page);
|
||||
- after `llmhost install-otp`, also a code from a paired authenticator app, which starts a
|
||||
session (sessions.py) -- and the key can be switched off here with dashboard_key_login;
|
||||
- after `llmhost install-oidc`, only people signed in through the OIDC provider (oidc.py).
|
||||
"""
|
||||
import hmac
|
||||
import html
|
||||
|
|
@ -18,6 +21,8 @@ from pathlib import Path
|
|||
|
||||
from .. import hfcache, hw, opencode, paths, plan, service
|
||||
from . import oidc as oidc_mod
|
||||
from . import sessions as sess_mod
|
||||
from .. import otp as otp_mod
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SAMPLE_SECONDS = 2
|
||||
|
|
@ -412,7 +417,49 @@ class Sampler:
|
|||
threading.Thread(target=fn, args=("model",), daemon=True).start()
|
||||
|
||||
|
||||
def make_handler(sampler, key, oidc=None):
|
||||
DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too
|
||||
|
||||
|
||||
def raw_file_url(repo, ref, name):
|
||||
"""Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the
|
||||
/raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https."""
|
||||
m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "")
|
||||
if not m:
|
||||
return None
|
||||
host, path = m.group(1), m.group(2)
|
||||
if host.lower() == "github.com":
|
||||
return f"https://raw.githubusercontent.com/{path}/{ref}/{name}"
|
||||
return f"https://{host}/{path}/raw/branch/{ref}/{name}"
|
||||
|
||||
|
||||
_installer = None
|
||||
|
||||
|
||||
def installer_url():
|
||||
"""The opencode installer's URL in the repo this server was installed from, so the
|
||||
command the Connect dialog gives out works for people who can't reach this dashboard
|
||||
(an API-only tunnel) and follows a fork. Falls back to the main repo."""
|
||||
global _installer
|
||||
if _installer is None:
|
||||
import subprocess
|
||||
def git(*args):
|
||||
try:
|
||||
r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5)
|
||||
return r.stdout.strip() if r.returncode == 0 else ""
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return ""
|
||||
ref = git("rev-parse", "--abbrev-ref", "HEAD")
|
||||
_installer = (raw_file_url(git("config", "--get", "remote.origin.url"),
|
||||
ref if ref and ref != "HEAD" else "main", "opencode-install.sh")
|
||||
or raw_file_url(DEFAULT_REPO, "main", "opencode-install.sh"))
|
||||
return _installer
|
||||
|
||||
|
||||
def make_handler(sampler, key, oidc=None, otp=None, key_login=True):
|
||||
"""oidc: an oidc.OIDC, which then decides alone. Otherwise the API key (unless
|
||||
key_login is off) and, with otp (an otp.Verifier), authenticator codes."""
|
||||
sessions = sess_mod.Sessions() # authenticator-code sign-ins, in key mode
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "llm-host"
|
||||
|
||||
|
|
@ -440,11 +487,45 @@ def make_handler(sampler, key, oidc=None):
|
|||
return True
|
||||
h = self.headers.get("Authorization", "")
|
||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
||||
if hmac.compare_digest(tok.encode(), key.encode()):
|
||||
if key_login and tok and hmac.compare_digest(tok.encode(), key.encode()):
|
||||
return True
|
||||
if sessions.get(self.headers.get("Cookie", "")) is not None:
|
||||
if self.command == "POST" and not self.same_host():
|
||||
self.send_json(403, {"error": "cross-origin request refused"})
|
||||
return False
|
||||
return True
|
||||
self.send_json(401, {"error": "unauthorized"})
|
||||
return False
|
||||
|
||||
def same_host(self):
|
||||
"""Key mode's check for cookie-authenticated POSTs: the page that sent it must
|
||||
be this dashboard, by whatever name it was reached (LAN or tunnel)."""
|
||||
o = self.headers.get("Origin") or self.headers.get("Referer") or ""
|
||||
netloc = urllib.parse.urlsplit(o).netloc.lower()
|
||||
return bool(netloc) and netloc == (self.headers.get("Host") or "").lower()
|
||||
|
||||
def via_https(self):
|
||||
# Behind the tunnel, HTTPS ends at the reverse proxy, which says so here. Only
|
||||
# used for the cookie's Secure flag, so a forged header can only weaken that.
|
||||
return self.headers.get("X-Forwarded-Proto", "").lower() == "https"
|
||||
|
||||
def read_json(self):
|
||||
try:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
return json.loads(self.rfile.read(min(n, 65536)) or b"{}") if n else {}
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def send_json_cookie(self, code, obj, cookie):
|
||||
body = json.dumps(obj).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def redirect(self, url, cookies=()):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", url)
|
||||
|
|
@ -475,8 +556,11 @@ def make_handler(sampler, key, oidc=None):
|
|||
|
||||
def auth_get(self, path, query):
|
||||
if path == "/auth/config":
|
||||
s = oidc.session(self.headers.get("Cookie", "")) if oidc else None
|
||||
return self.send_json(200, {"mode": "oidc" if oidc else "key",
|
||||
if oidc:
|
||||
s = oidc.session(self.headers.get("Cookie", ""))
|
||||
return self.send_json(200, {"mode": "oidc", "user": s and s["user"], "name": s and s["name"]})
|
||||
s = sessions.get(self.headers.get("Cookie", ""))
|
||||
return self.send_json(200, {"mode": "key", "key": key_login, "otp": otp is not None,
|
||||
"user": s and s["user"], "name": s and s["name"]})
|
||||
if not oidc:
|
||||
return self.send_json(404, {"error": "not found"})
|
||||
|
|
@ -527,7 +611,8 @@ def make_handler(sampler, key, oidc=None):
|
|||
cfg = paths.load_config() or sampler.cfg
|
||||
block = opencode.provider_block(cfg, "HOST", "KEYFILE", "LABEL")
|
||||
self.send_json(200, {"key": key, "api_port": cfg["api_port"],
|
||||
"model": plan.SERVED_ALIAS, "opencode": block})
|
||||
"model": plan.SERVED_ALIAS, "opencode": block,
|
||||
"installer": installer_url()})
|
||||
elif path == "/api/logs":
|
||||
if self.authed():
|
||||
lines = [l for l in service.logs("model", 1500)
|
||||
|
|
@ -538,17 +623,29 @@ def make_handler(sampler, key, oidc=None):
|
|||
|
||||
def do_POST(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/auth/logout" and oidc:
|
||||
if not oidc.same_origin(self.headers):
|
||||
if path == "/auth/logout":
|
||||
if not (oidc.same_origin(self.headers) if oidc else self.same_host()):
|
||||
return self.send_json(403, {"error": "cross-origin request refused"})
|
||||
oidc.end(self.headers.get("Cookie", ""))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0))
|
||||
self.send_header("Content-Length", "11")
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"ok": true}')
|
||||
return
|
||||
(oidc or sessions).end(self.headers.get("Cookie", ""))
|
||||
clear = (oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0) if oidc
|
||||
else sess_mod.cookie(sess_mod.SESSION_COOKIE, "", 0, self.via_https()))
|
||||
return self.send_json_cookie(200, {"ok": True}, clear)
|
||||
if path == "/auth/otp":
|
||||
if oidc or otp is None:
|
||||
return self.send_json(404, {"error": "not found"})
|
||||
if not self.same_host():
|
||||
return self.send_json(403, {"error": "cross-origin request refused"})
|
||||
data = self.read_json()
|
||||
result = otp.check(str((data or {}).get("code", "")))
|
||||
if result == "locked":
|
||||
return self.send_json(429, {"error": "too many wrong codes; try again in a few minutes",
|
||||
"retry_after": otp.locked_for()})
|
||||
if result != "ok":
|
||||
return self.send_json(401, {"error": "that code is wrong, expired or already used"})
|
||||
sid = sessions.create("authenticator", "Authenticator app")
|
||||
print("llm-host dashboard: signed in with an authenticator code", flush=True)
|
||||
return self.send_json_cookie(200, {"ok": True}, sess_mod.cookie(
|
||||
sess_mod.SESSION_COOKIE, sid, sess_mod.SESSION_TTL, self.via_https()))
|
||||
if not self.authed():
|
||||
return
|
||||
try:
|
||||
|
|
@ -588,11 +685,15 @@ def serve():
|
|||
key = paths.api_key()
|
||||
sampler = Sampler(cfg, key)
|
||||
threading.Thread(target=sampler.loop, daemon=True).start()
|
||||
auth = None
|
||||
auth = otp = None
|
||||
conf = cfg.get("dashboard_auth") or {}
|
||||
if conf.get("mode") == "oidc":
|
||||
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth))
|
||||
how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key"
|
||||
elif paths.OTP_SECRET_FILE.exists():
|
||||
otp = otp_mod.Verifier(paths.read_secret(paths.OTP_SECRET_FILE, "authenticator secret", "llmhost install-otp"))
|
||||
key_login = cfg.get("dashboard_key_login", True) or otp is None # never lock everyone out
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth, otp, key_login))
|
||||
how = (f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else
|
||||
" or ".join((["API key"] if key_login else []) + (["authenticator code"] if otp else [])))
|
||||
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
|
||||
srv.serve_forever()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue