install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard

A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt`
is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and
switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups
or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a
service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt`
shows the tunnel (and `logs -f` now follows the service it was asked for).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-05 21:44:09 -08:00
parent d07a92e5b5
commit e814a2359d
11 changed files with 1155 additions and 26 deletions

View file

@ -117,7 +117,11 @@ def carried_settings(old, names):
`llmhost update` would quietly put every model back to "Model default". Models that no
longer fit lose their setting along with their plan."""
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
return {"reasoning": kept} if kept else {}
out = {"reasoning": kept} if kept else {}
for k in ("newt", "dashboard_auth"): # set by `llmhost install-newt`, not by the plan
if old.get(k):
out[k] = old[k]
return out
def cmd_setup(a):
@ -190,6 +194,10 @@ def cmd_setup(a):
if not a.no_start:
service.restart("web")
service.restart("model")
if cfg.get("newt") and service.installed("newt"):
from . import newt
if newt.ensure_binary(say):
service.restart("newt")
host = default_host()
say(f"""
Done.
@ -328,7 +336,7 @@ def _service_check():
def cmd_status(a):
cfg = _service_check()
host = default_host()
for name in service.NAMES:
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
st, up = service.state(name)
upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else ""
say(f"{name:6} {st}{upt}")
@ -340,6 +348,12 @@ def cmd_status(a):
except Exception:
say(f"active model {cfg['active']} is not answering yet")
say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}")
d = cfg.get("dashboard_auth") or {}
if d.get("mode") == "oidc":
who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])])
say(f"public {d['public_url']} (sign-in via {d['issuer']}; {who})")
if cfg.get("newt"):
say(f"tunnel newt -> {cfg['newt']['endpoint']}")
def cmd_models(a):
@ -375,9 +389,10 @@ def cmd_ctl(a):
def cmd_logs(a):
_service_check()
name = "newt" if a.newt else "web" if a.web else "model"
if a.follow:
os.execvp(service.log_command("model")[0], service.log_command("model"))
for line in service.logs("web" if a.web else "model", a.n):
os.execvp(service.log_command(name)[0], service.log_command(name))
for line in service.logs(name, a.n):
say(line)
@ -466,6 +481,139 @@ def cmd_key(a):
say(paths.api_key())
def _restart_if_running(name):
if service.state(name)[0] in ("active", "activating"):
if not service.restart(name):
say(f"Couldn't restart the {name} service; see `llmhost logs --{name}`.")
def lan_ip():
"""This machine's address on its default route -- what newt, running here, should dial
to reach the services. Connecting a UDP socket sends nothing."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("192.0.2.1", 9)) # TEST-NET-1: never routed anywhere
return s.getsockname()[0]
except OSError:
return "127.0.0.1"
finally:
s.close()
def _ask(label, given, default=None, flag=None, secret=False, env=None):
"""A value from its flag, its env var, or a prompt (keeping `default` on Enter).
Without a terminal, a value that's still missing is an error naming the flag."""
if given:
return given
if env and os.environ.get(env):
return os.environ[env]
if not sys.stdin.isatty():
if default:
return default
sys.exit(f"missing {flag or ('$' + env)}" + (f" (or ${env})" if flag and env else ""))
hint = " [keep current]" if secret and default else (f" [{default}]" if default else "")
if secret:
import getpass
v = getpass.getpass(f"{label}{hint}: ").strip()
else:
v = input(f"{label}{hint}: ").strip()
v = v or default
if not v:
sys.exit(f"{label} is required")
return v
def _check_url(label, url, bare=True):
import urllib.parse
u = urllib.parse.urlsplit(url)
if u.scheme not in ("http", "https") or not u.netloc or (bare and u.path.strip("/")):
sys.exit(f"{label} should look like https://host.example.com, not {url!r}")
if u.scheme != "https":
sys.exit(f"{label} must be https:// -- this is the address people reach from the internet")
return url.rstrip("/")
def cmd_install_newt(a):
"""Upgrade a LAN install for the internet: newt tunnel + OIDC sign-in on the dashboard."""
from . import newt
from .web import oidc
cfg = _service_check()
old_n, old_d = cfg.get("newt") or {}, cfg.get("dashboard_auth") or {}
newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for
say("Pangolin site (Pangolin: Sites -> Add Site -> Newt):")
endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint", a.endpoint, old_n.get("endpoint"), "--endpoint"))
site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id")
have_newt_secret = paths.NEWT_SECRET_FILE.exists() and old_n
newt_secret = _ask(" Newt secret", None, "keep" if have_newt_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
say("\nDashboard sign-in (an OIDC client registered with your provider):")
public_url = _check_url("Dashboard URL", _ask(" Dashboard's public URL", a.public_url, old_d.get("public_url"), "--public-url"))
issuer = _check_url("Issuer", _ask(" OIDC issuer", a.issuer, old_d.get("issuer"), "--issuer"), bare=False)
client_id = _ask(" Client ID", a.client_id, old_d.get("client_id") or "llm-host", "--client-id")
have_oidc_secret = paths.OIDC_SECRET_FILE.exists() and old_d
oidc_secret = _ask(" Client secret", None, "keep" if have_oidc_secret else None, secret=True, env="LLMHOST_OIDC_SECRET")
groups, users = a.allow_group or [], a.allow_user or []
if not (groups or users):
# A re-run keeps the allow list unless it's given again.
groups, users = old_d.get("allowed_groups", []), old_d.get("allowed_users", [])
if not (groups or users):
groups = [g.strip() for g in _ask(" Groups allowed in (comma-separated)", None, None,
"--allow-group").split(",") if g.strip()]
if not (groups or users):
sys.exit("say who may sign in: --allow-group <group> and/or --allow-user <username>")
dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url,
"allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))}
secret_for_check = paths.oidc_secret() if oidc_secret == "keep" else oidc_secret
try:
oidc.OIDC(dash, secret_for_check).discovery()
except oidc.AuthError as e:
sys.exit(str(e))
newt.ensure_binary(say)
if newt_secret != "keep":
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
if oidc_secret != "keep":
paths.save_secret(paths.OIDC_SECRET_FILE, oidc_secret)
cfg["newt"] = {"endpoint": endpoint, "id": site_id}
cfg["dashboard_auth"] = dash
paths.save_config(cfg)
service.install("newt")
if not service.restart("newt"):
say("newt didn't start; see `llmhost logs --newt`.")
_restart_if_running("web")
ip = lan_ip()
say(f"""
Done. newt is running and the dashboard now signs in through {issuer};
the API key no longer opens it (the API itself still uses the key).
In Pangolin, add two HTTP resources on this site, with Pangolin's own SSO off on both
(llm-host checks the API key on one and signs people in on the other):
dashboard {public_url} -> http://{ip}:{cfg['web_port']}
API <a host of your choice> -> http://{ip}:{cfg['api_port']}
Point them at {ip}, not localhost: requests from localhost count as local here.
Register this redirect URI with your OIDC client: {public_url}/auth/callback
Clients use https://<API host>/v1 with the API key (`llmhost key`).
Undo all of this with: llmhost remove-newt""")
def cmd_remove_newt(a):
"""Back to a LAN-only install: stop newt, and the dashboard takes the API key again."""
cfg = _service_check()
if service.installed("newt"):
service.uninstall("newt")
shutil.rmtree(paths.NEWT_DIR, ignore_errors=True)
paths.NEWT_SECRET_FILE.unlink(missing_ok=True)
paths.OIDC_SECRET_FILE.unlink(missing_ok=True)
had = bool(cfg.pop("newt", None)) | bool(cfg.pop("dashboard_auth", None))
paths.save_config(cfg)
_restart_if_running("web")
say("Removed newt; the dashboard takes the API key again." if had else "newt wasn't installed.")
def cmd_download(a):
cfg = _service_check()
m = next((x for x in cfg["models"] if x["name"] == a.model), None)
@ -554,7 +702,7 @@ def cmd_uninstall(a):
# Read the catalog now: --purge deletes it along with the rest of llm-host.
cached = cached_catalog_models()
cfg = paths.load_config() or {}
for name in service.NAMES:
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
service.uninstall(name)
# Stopping returns before the processes have exited (launchd especially). Wait, so a
# reinstall right after this finds the ports free instead of moving to other ones.
@ -563,7 +711,7 @@ def cmd_uninstall(a):
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
with Spinner("Waiting for the services to exit"):
wait_ports_free(ours, timeout=30)
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test", "newt"):
shutil.rmtree(paths.DATA / d, ignore_errors=True)
say("Removed services and backend environments.")
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
@ -637,6 +785,11 @@ def cmd_run_model(a):
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
def cmd_run_newt(a):
from . import newt
newt.run()
def cmd_run_web(a):
_service_check()
service.trim_log("web")
@ -679,10 +832,22 @@ def main(argv=None):
s.add_argument("-f", "--follow", action="store_true")
s.add_argument("-n", type=int, default=100)
s.add_argument("--web", action="store_true", help="dashboard logs instead")
s.add_argument("--newt", action="store_true", help="tunnel logs instead")
s.set_defaults(fn=cmd_logs)
sub.add_parser("watch", help="show download and loading progress until the model is ready"
).set_defaults(fn=cmd_watch)
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
s = sub.add_parser("install-newt", help="reach this server from the internet: newt tunnel + OIDC sign-in on the dashboard")
s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com")
s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)")
s.add_argument("--public-url", help="the dashboard's public address, e.g. https://llm-dash.example.com")
s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com")
s.add_argument("--client-id", help="OIDC client ID (default llm-host; secret: prompted, or $LLMHOST_OIDC_SECRET)")
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed into the dashboard (repeatable)")
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed into the dashboard (repeatable)")
s.set_defaults(fn=cmd_install_newt)
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel, dashboard back to the API key"
).set_defaults(fn=cmd_remove_newt)
s = sub.add_parser("download", help="download a model ahead of time")
s.add_argument("model")
s.set_defaults(fn=cmd_download)
@ -710,6 +875,7 @@ def main(argv=None):
s.set_defaults(fn=cmd_uninstall)
sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
sub.add_parser("run-web").set_defaults(fn=cmd_run_web)
sub.add_parser("run-newt").set_defaults(fn=cmd_run_newt)
a = ap.parse_args(argv)
a.fn(a)

89
llmhost/newt.py Normal file
View file

@ -0,0 +1,89 @@
"""Optional internet access through a Pangolin tunnel (newt). Stdlib only.
`llmhost install-newt` is the upgrade path from a LAN install. It
- downloads a pinned newt release and checks it against the sha256 below,
- runs it as a third user service ("newt", via `llmhost run-newt`), which dials out to
the Pangolin server -- nothing on this machine is opened to the internet,
- and switches the dashboard to OIDC sign-in (web/oidc.py), because once it's public the
API key is too much power to hand out: it also stops and switches the model.
newt runs in userspace (no root, no kernel WireGuard). Its site secret is kept in
~/.config/llm-host/newt_secret (0600) and handed over in its environment at start, never
written into the service file.
"""
import hashlib
import os
import platform
import tempfile
import urllib.request
from . import paths
VERSION = "1.19.0"
# From the GitHub release's asset digests for VERSION.
SHA256 = {
"linux_amd64": "6d40e223fa49d8bcfa9b7094208c58ff616997979bff7c884d0af61fcc1c5376",
"linux_arm64": "2a282e3edda7be17f092ac58aff0ec6dac9ddd152a642e8e61e6d625f2abe696",
"darwin_arm64": "bdc93f811e017affb893eab8d924dfe72ea63e1bdeaf85decec1afb711288ee5",
"darwin_amd64": "d44a4fd5526174788622e4eebea55ef268df19c85fc67766d0f27e23eb8800fa",
}
URL = "https://github.com/fosrl/newt/releases/download/{version}/newt_{plat}"
def platform_tag() -> str:
os_name = {"Linux": "linux", "Darwin": "darwin"}.get(platform.system())
arch = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower())
tag = f"{os_name}_{arch}"
if tag not in SHA256:
raise SystemExit(f"newt isn't packaged here for {platform.system()} {platform.machine()}")
return tag
def binary() -> "os.PathLike":
return paths.NEWT_DIR / "newt"
def installed_version():
try:
return (paths.NEWT_DIR / "VERSION").read_text().strip()
except OSError:
return None
def ensure_binary(say=print, fetch=None) -> bool:
"""Install the pinned newt if it isn't there already. Returns True if it changed."""
if installed_version() == VERSION and binary().exists():
return False
tag = platform_tag()
url = URL.format(version=VERSION, plat=tag)
say(f"Downloading newt {VERSION} ({tag})…")
data = (fetch or _fetch)(url)
got = hashlib.sha256(data).hexdigest()
if got != SHA256[tag]:
raise SystemExit(f"newt download didn't match its checksum (got {got}); not installing it")
paths.NEWT_DIR.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=paths.NEWT_DIR, prefix=".newt.")
with os.fdopen(fd, "wb") as f:
f.write(data)
os.chmod(tmp, 0o755)
os.replace(tmp, binary())
(paths.NEWT_DIR / "VERSION").write_text(VERSION + "\n")
return True
def _fetch(url) -> bytes:
with urllib.request.urlopen(url, timeout=300) as r:
return r.read()
def run():
"""The service's entry point: exec newt with its credentials in the environment."""
cfg = paths.load_config()
conf = cfg.get("newt") or {}
if not conf.get("endpoint") or not conf.get("id"):
raise SystemExit("newt isn't configured; run `llmhost install-newt`")
secret = paths.read_secret(paths.NEWT_SECRET_FILE, "newt site secret", "llmhost install-newt")
env = {**os.environ, "PANGOLIN_ENDPOINT": conf["endpoint"], "NEWT_ID": conf["id"],
"NEWT_SECRET": secret, "LOG_LEVEL": conf.get("log_level", "INFO")}
exe = str(binary())
os.execve(exe, [exe], env)

View file

@ -6,6 +6,9 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA)
~/.config/llm-host/config.json plan + settings
~/.config/llm-host/api_key API key (0600)
~/.local/share/llm-host/newt newt binary, after `llmhost install-newt`
~/.config/llm-host/oidc_secret dashboard sign-in client secret (0600), after install-newt
~/.config/llm-host/newt_secret Pangolin site secret (0600), after install-newt
"""
import json
import os
@ -21,6 +24,9 @@ DATA = Path(os.environ.get("LLMHOST_HOME", HOME / ".local/share/llm-host"))
CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host"))
CONFIG_FILE = CONFIG_DIR / "config.json"
KEY_FILE = CONFIG_DIR / "api_key"
OIDC_SECRET_FILE = CONFIG_DIR / "oidc_secret"
NEWT_SECRET_FILE = CONFIG_DIR / "newt_secret"
NEWT_DIR = DATA / "newt"
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
BIN_DIR = HOME / ".local/bin"
SHIM = BIN_DIR / "llmhost"
@ -66,3 +72,23 @@ def api_key(create: bool = False) -> str:
with os.fdopen(fd, "w") as f:
f.write(key + "\n")
return key
def read_secret(path, what, fix) -> str:
try:
return path.read_text().strip()
except OSError:
raise SystemExit(f"No {what} at {path}; run `{fix}` again.")
def save_secret(path, secret: str) -> None:
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(secret + "\n")
os.chmod(path, 0o600) # O_CREAT's mode doesn't apply to a file that already existed
def oidc_secret() -> str:
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-newt")

View file

@ -1,6 +1,7 @@
"""Background services: systemd --user on Linux, launchd agents on macOS.
Two services: "model" (the inference server) and "web" (dashboard). Both run `llmhost run-<name>`.
Two services: "model" (the inference server) and "web" (dashboard), plus "newt" (the
Pangolin tunnel) only after `llmhost install-newt`. Each runs `llmhost run-<name>`.
"""
import os
import re
@ -10,7 +11,8 @@ from pathlib import Path
from . import paths
NAMES = ("model", "web")
NAMES = ("model", "web") # what setup installs
OPTIONAL = ("newt",) # installed by their own command
def _run(cmd, timeout=60):
@ -32,7 +34,8 @@ def _unit_path(name):
def _systemd_install(name):
desc = {"model": "llm-host model server", "web": "llm-host dashboard"}[name]
desc = {"model": "llm-host model server", "web": "llm-host dashboard",
"newt": "llm-host tunnel (newt)"}[name]
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
p = _unit_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
@ -104,6 +107,10 @@ def install(name):
_run(["systemctl", "--user", "enable", _unit(name)])
def installed(name):
return (_plist_path(name) if paths.IS_MAC else _unit_path(name)).exists()
def enable_linger():
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
if paths.IS_MAC:

View file

@ -76,13 +76,14 @@ button.small { font-size: 12px; padding: 4px 10px; }
}
.effort select:disabled { color: var(--muted); }
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
button {
button, a.btn {
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
}
button:hover:not(:disabled) { border-color: var(--faint); }
button:disabled { opacity: .45; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
a.btn { display: inline-block; text-decoration: none; }
button.primary, a.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
button.danger { color: var(--bad); }
.profiles { display: flex; flex-direction: column; gap: 8px; }
@ -169,6 +170,7 @@ pre {
<span id="phase" class="pill">…</span>
<span class="spacer"></span>
<span class="meta" id="uptime"></span>
<span class="meta" id="whoami" hidden></span>
<button id="logout" title="Forget API key">Sign out</button>
</header>
@ -268,6 +270,11 @@ pre {
<div class="err" id="auth-err"></div>
<button class="primary" type="submit">Continue</button>
</form>
<div class="dialog" id="auth-oidc" hidden>
<h3>Sign in</h3>
<p id="auth-oidc-text">This dashboard signs in through your identity provider.</p>
<a class="btn primary" href="/auth/login" id="auth-oidc-go">Sign in</a>
</div>
</div>
<div class="toast" id="toast"></div>
@ -275,6 +282,9 @@ pre {
const $ = (id) => document.getElementById(id);
let KEY = null;
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
// "key": the API key, typed in and kept in this browser. "oidc": a session cookie set by
// signing in at the provider (/auth/login); the key isn't accepted then.
let AUTH = { mode: "key" };
let state = null;
let logTimer = null;
@ -287,14 +297,23 @@ function toast(msg) {
}
async function api(path, opts = {}) {
const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } });
if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); }
const headers = { "Content-Type": "application/json" };
if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY;
const r = await fetch(path, { ...opts, headers, credentials: "same-origin" });
if (r.status === 401) { showAuth(AUTH.mode === "key" ? "That key was rejected." : ""); throw new Error("unauthorized"); }
const body = await r.json();
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
}
function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); }
function showAuth(err = "") {
if (AUTH.mode === "oidc") {
$("auth-form").hidden = true; $("auth-oidc").hidden = false;
$("auth").classList.add("show"); $("auth-oidc-go").focus();
return;
}
$("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus();
}
$("auth-form").addEventListener("submit", (e) => {
e.preventDefault();
KEY = $("auth-key").value.trim();
@ -302,7 +321,14 @@ $("auth-form").addEventListener("submit", (e) => {
$("auth").classList.remove("show");
poll();
});
$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); };
$("logout").onclick = async () => {
if (AUTH.mode === "oidc") {
try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {}
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); showAuth();
return;
}
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth();
};
const fmt = {
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
@ -692,12 +718,26 @@ $("logs").addEventListener("toggle", () => {
let pollTimer = null;
async function poll() {
clearTimeout(pollTimer);
if (!KEY) { showAuth(); return; }
if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; }
try { render(await api("/api/status")); }
catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } }
catch (e) {
if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in
if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; }
}
pollTimer = setTimeout(poll, 2000);
}
poll();
(async () => {
try {
const r = await fetch("/auth/config", { credentials: "same-origin" });
if (r.ok) AUTH = await r.json();
} catch (e) {}
if (AUTH.mode === "oidc") {
$("logout").title = "Sign out of this dashboard";
if (AUTH.user) { $("whoami").textContent = AUTH.name || AUTH.user; $("whoami").hidden = false; }
}
poll();
})();
</script>
</body>
</html>

236
llmhost/web/oidc.py Normal file
View file

@ -0,0 +1,236 @@
"""Dashboard sign-in through an OpenID Connect provider. Stdlib only.
Off unless config.json has a "dashboard_auth" block with mode "oidc" (`llmhost install-newt` sets it); then it replaces the
API key on the dashboard (the API on api_port still takes the key -- that's for clients).
The flow is the authorization-code flow of a confidential client, with PKCE:
/auth/login -> 302 to the provider, with state, nonce and an S256 code challenge.
The state is also set in a short-lived cookie, so a callback only
completes in the browser that started it (no login CSRF).
/auth/callback -> code exchanged at the token endpoint with the client secret, the
ID token's claims checked, groups read from userinfo, the allow
list applied, and a session cookie set.
/auth/logout -> POST; drops the session.
The ID token comes straight from the token endpoint over TLS, which OIDC Core 3.1.3.7 lets
a client rely on in place of checking its signature; its iss/aud/azp/exp/nonce are still
checked. Sessions live in memory, so a dashboard restart signs everyone out.
"""
import base64
import hashlib
import hmac
import json
import secrets
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
SESSION_COOKIE = "llmhost_session"
STATE_COOKIE = "llmhost_oidc_state"
SESSION_TTL = 12 * 3600
LOGIN_TTL = 600 # how long a started sign-in may take to come back
MAX_PENDING = 256 # unfinished sign-ins kept at once
CLOCK_SKEW = 120
SCOPES = "openid profile email groups"
class AuthError(Exception):
"""A sign-in that can't complete; the message is safe to show the user."""
def b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def jwt_claims(token: str) -> dict:
try:
payload = token.split(".")[1]
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
except (IndexError, ValueError):
raise AuthError("the provider sent an unreadable ID token")
def parse_cookies(header: str) -> dict:
out = {}
for part in (header or "").split(";"):
k, sep, v = part.strip().partition("=")
if sep:
out.setdefault(k, v)
return out
def origin_of(url: str) -> str:
u = urllib.parse.urlsplit(url)
return f"{u.scheme}://{u.netloc}".lower()
class OIDC:
def __init__(self, conf: dict, client_secret: str, http=None):
self.issuer = conf["issuer"].rstrip("/")
self.client_id = conf["client_id"]
self.secret = client_secret
self.public_url = conf["public_url"].rstrip("/")
self.redirect_uri = self.public_url + "/auth/callback"
self.origin = origin_of(self.public_url)
self.secure = self.public_url.startswith("https://")
self.allowed_groups = set(conf.get("allowed_groups") or [])
self.allowed_users = set(conf.get("allowed_users") or [])
if not (self.allowed_groups or self.allowed_users):
raise ValueError("dashboard_auth needs allowed_groups or allowed_users")
self.http = http or self._http
self.lock = threading.Lock()
self.pending = {} # state -> {nonce, verifier, t}
self.sessions = {} # sha256(session id) -> {user, name, exp}
self._disco = None
# -- provider ---------------------------------------------------------------------
@staticmethod
def _http(method, url, data=None, headers=None):
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def discovery(self) -> dict:
if self._disco is None:
try:
st, body = self.http("GET", self.issuer + "/.well-known/openid-configuration")
d = json.loads(body) if st == 200 else None
except (OSError, ValueError):
d = None
if not d or d.get("issuer", "").rstrip("/") != self.issuer:
raise AuthError(f"couldn't reach the sign-in provider at {self.issuer}")
self._disco = d
return self._disco
# -- sign-in ----------------------------------------------------------------------
def start(self):
"""Begin a sign-in: (provider URL to redirect to, state for the state cookie)."""
d = self.discovery()
state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
now = time.time()
with self.lock:
for s in [s for s, p in self.pending.items() if now - p["t"] > LOGIN_TTL]:
del self.pending[s]
if len(self.pending) >= MAX_PENDING:
del self.pending[min(self.pending, key=lambda s: self.pending[s]["t"])]
self.pending[state] = {"nonce": nonce, "verifier": verifier, "t": now}
q = urllib.parse.urlencode({
"response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri,
"scope": SCOPES, "state": state, "nonce": nonce,
"code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
"code_challenge_method": "S256"})
return f"{d['authorization_endpoint']}?{q}", state
def finish(self, params: dict, cookie_state: str) -> dict:
"""Complete a sign-in from the callback's query. Returns the new session
{"id", "user", "name"}; raises AuthError for anything that doesn't check out."""
if params.get("error"):
raise AuthError(f"the provider said: {params.get('error_description') or params['error']}")
state = params.get("state", "")
if not state or not cookie_state or not hmac.compare_digest(state, cookie_state):
raise AuthError("this sign-in was started in a different browser or tab; try again")
with self.lock:
p = self.pending.pop(state, None)
if not p or time.time() - p["t"] > LOGIN_TTL:
raise AuthError("this sign-in expired; try again")
d = self.discovery()
if "iss" in params and params["iss"].rstrip("/") != self.issuer:
raise AuthError("the response came from a different provider")
code = params.get("code")
if not code:
raise AuthError("the provider sent no authorization code")
basic = base64.b64encode(f"{urllib.parse.quote(self.client_id, safe='')}:"
f"{urllib.parse.quote(self.secret, safe='')}".encode()).decode()
st, body = self.http("POST", d["token_endpoint"], urllib.parse.urlencode({
"grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri,
"code_verifier": p["verifier"]}).encode(), {
"Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"})
try:
tok = json.loads(body)
except ValueError:
tok = {}
if st != 200 or "id_token" not in tok:
raise AuthError(f"the provider refused the code ({tok.get('error') or st})")
c = jwt_claims(tok["id_token"])
now = time.time()
aud = c.get("aud")
auds = aud if isinstance(aud, list) else [aud]
if c.get("iss", "").rstrip("/") != self.issuer:
raise AuthError("the ID token is from a different provider")
if self.client_id not in auds or (len(auds) > 1 and c.get("azp") != self.client_id):
raise AuthError("the ID token was issued to a different client")
if not isinstance(c.get("exp"), (int, float)) or c["exp"] < now - CLOCK_SKEW:
raise AuthError("the ID token has expired")
if not hmac.compare_digest(str(c.get("nonce", "")), p["nonce"]):
raise AuthError("the ID token doesn't belong to this sign-in")
info = dict(c)
if d.get("userinfo_endpoint") and tok.get("access_token"):
st, body = self.http("GET", d["userinfo_endpoint"], None, {
"Authorization": f"Bearer {tok['access_token']}", "Accept": "application/json"})
try:
u = json.loads(body) if st == 200 else {}
except ValueError:
u = {} # a signed/encrypted userinfo isn't JSON; the ID token's claims stand
if u.get("sub") == c.get("sub"):
info.update(u)
user = info.get("preferred_username") or info.get("email") or info.get("sub")
groups = set(info.get("groups") or [])
if user not in self.allowed_users and not (groups & self.allowed_groups):
raise AuthError(f"signed in as {user}, but that account isn't allowed on this dashboard")
sid = secrets.token_urlsafe(32)
with self.lock:
for h in [h for h, s in self.sessions.items() if s["exp"] < now]:
del self.sessions[h]
self.sessions[self._h(sid)] = {"user": user, "name": info.get("name") or user,
"exp": now + SESSION_TTL}
return {"id": sid, "user": user, "name": info.get("name") or user}
# -- sessions ---------------------------------------------------------------------
@staticmethod
def _h(sid: str) -> str:
return hashlib.sha256(sid.encode()).hexdigest()
def session(self, cookie_header: str):
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
if not sid:
return None
with self.lock:
s = self.sessions.get(self._h(sid))
if s and s["exp"] < time.time():
del self.sessions[self._h(sid)]
s = None
return s
def end(self, cookie_header: str):
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
if sid:
with self.lock:
self.sessions.pop(self._h(sid), None)
def same_origin(self, headers) -> bool:
"""For state-changing requests: the browser's Origin (or Referer) must be the
dashboard's own. SameSite=Lax already keeps the cookie off cross-site POSTs;
this is the second lock on that door."""
o = headers.get("Origin") or (origin_of(headers["Referer"]) if headers.get("Referer") else "")
return o.lower() == self.origin
def cookie(self, name, value, max_age, path="/"):
attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"]
if self.secure:
attrs.append("Secure")
return "; ".join(attrs)

View file

@ -1,19 +1,23 @@
"""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.
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).
"""
import hmac
import html
import json
import re
import socket
import threading
import time
import urllib.parse
import urllib.request
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .. import hfcache, hw, opencode, paths, plan, service
from . import oidc as oidc_mod
HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2
@ -408,7 +412,7 @@ class Sampler:
threading.Thread(target=fn, args=("model",), daemon=True).start()
def make_handler(sampler, key):
def make_handler(sampler, key, oidc=None):
class Handler(BaseHTTPRequestHandler):
server_version = "llm-host"
@ -425,6 +429,15 @@ def make_handler(sampler, key):
self.wfile.write(body)
def authed(self):
if oidc:
# Signed in through the provider; the API key isn't accepted here.
if oidc.session(self.headers.get("Cookie", "")) is None:
self.send_json(401, {"error": "unauthorized", "login": "/auth/login"})
return False
if self.command == "POST" and not oidc.same_origin(self.headers):
self.send_json(403, {"error": "cross-origin request refused"})
return False
return True
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
@ -432,8 +445,67 @@ def make_handler(sampler, key):
self.send_json(401, {"error": "unauthorized"})
return False
def redirect(self, url, cookies=()):
self.send_response(302)
self.send_header("Location", url)
self.send_header("Cache-Control", "no-store")
for c in cookies:
self.send_header("Set-Cookie", c)
self.send_header("Content-Length", "0")
self.end_headers()
def auth_page(self, code, msg):
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
f"<title>llm-host sign-in</title><body style='font:15px system-ui;margin:3em auto;"
f"max-width:32em;padding:0 16px'><h2>Couldn't sign you in</h2><p>{html.escape(msg)}</p>"
f"<p><a href='/auth/login'>Try again</a></p>").encode()
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/"))
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def on_public_host(self):
"""A session cookie only exists on the public URL's host, so a visit by any
other name (mybox.local:11340) is sent there instead of to a login loop."""
host = (self.headers.get("Host") or "").lower()
return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower()
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",
"user": s and s["user"], "name": s and s["name"]})
if not oidc:
return self.send_json(404, {"error": "not found"})
if path == "/auth/login":
if not self.on_public_host():
return self.redirect(oidc.public_url + "/auth/login")
try:
url, state = oidc.start()
except oidc_mod.AuthError as e:
return self.auth_page(502, str(e))
return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")])
if path == "/auth/callback":
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "")
try:
s = oidc.finish(params, cookie_state)
except oidc_mod.AuthError as e:
return self.auth_page(403, str(e))
print(f"llm-host dashboard: {s['user']} signed in", flush=True)
return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL),
oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")])
self.send_json(404, {"error": "not found"})
def do_GET(self):
path = self.path.split("?", 1)[0]
path, _, query = self.path.partition("?")
if path.startswith("/auth/"):
return self.auth_get(path, query)
if oidc and path in ("/", "/index.html") and not self.on_public_host():
return self.redirect(oidc.public_url + "/")
if path in ("/", "/index.html"):
body = (HERE / "index.html").read_bytes()
self.send_response(200)
@ -455,6 +527,17 @@ def make_handler(sampler, key):
def do_POST(self):
path = self.path.split("?", 1)[0]
if path == "/auth/logout" and oidc:
if not oidc.same_origin(self.headers):
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
if not self.authed():
return
try:
@ -494,6 +577,11 @@ def serve():
key = paths.api_key()
sampler = Sampler(cfg, key)
threading.Thread(target=sampler.loop, daemon=True).start()
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
auth = 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"
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
srv.serve_forever()