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:
neil 2026-11-06 15:56:54 -08:00
parent e6ff4ce909
commit c8b70afdbf
20 changed files with 1715 additions and 239 deletions

View file

@ -8,6 +8,7 @@ import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.request
from . import hfcache, hw, opencode, paths, plan, service
@ -118,8 +119,8 @@ def carried_settings(old, names):
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}
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):
for k in ("newt", "dashboard_auth", "dashboard_key_login"): # set by install-*/expose-dashboard, not the plan
if old.get(k) is not None: # dashboard_key_login is False when it matters
out[k] = old[k]
return out
@ -351,7 +352,11 @@ def cmd_status(a):
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})")
say(f"sign-in OIDC via {d['issuer']} at {d['public_url']} ({who})")
else:
ways = (["API key"] if cfg.get("dashboard_key_login", True) or not paths.OTP_SECRET_FILE.exists() else []) \
+ (["authenticator code"] if paths.OTP_SECRET_FILE.exists() else [])
say(f"sign-in {' or '.join(ways)}")
if cfg.get("newt"):
say(f"tunnel newt -> {cfg['newt']['endpoint']}")
@ -534,25 +539,67 @@ def _check_url(label, url, bare=True):
def cmd_install_newt(a):
"""Upgrade a LAN install for the internet: newt tunnel + OIDC sign-in on the dashboard."""
"""Reach the API from the internet through a Pangolin tunnel. The dashboard stays on
the LAN: publishing it is a separate, deliberate step (`llmhost expose-dashboard`)."""
from . import newt
from .web import oidc
cfg = _service_check()
old_n, old_d = cfg.get("newt") or {}, cfg.get("dashboard_auth") or {}
old_n = cfg.get("newt") 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")
have_secret = paths.NEWT_SECRET_FILE.exists() and old_n
newt_secret = _ask(" Newt secret", None, "keep" if have_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"))
newt.ensure_binary(say)
if newt_secret != "keep":
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
cfg["newt"] = {"endpoint": endpoint, "id": site_id}
paths.save_config(cfg)
service.install("newt")
if not service.restart("newt"):
say("newt didn't start; see `llmhost logs --newt`.")
ip = lan_ip()
say(f"""
Done. newt is running. In Pangolin, add an HTTP resource on this site for the API:
<a host of your choice> -> http://{ip}:{cfg['api_port']}
with Pangolin's own authentication off (llm-host checks the API key). Point it at {ip}, not
localhost: requests from localhost count as local here.
Clients then use https://<that host>/v1 with the API key; for opencode, see the dashboard's
Connect button, or opencode-install.sh in the llm-host repo.
The dashboard stays on your local network. To put it online too, first give it a sign-in
that isn't the API key you hand out (`llmhost install-oidc` or `llmhost install-otp`), then
run `llmhost expose-dashboard`. Undo the tunnel with: llmhost remove-newt""")
def cmd_remove_newt(a):
"""Back to LAN-only: stop and remove newt. The dashboard's sign-in is left as it is."""
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)
had = bool(cfg.pop("newt", None))
paths.save_config(cfg)
say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.")
def cmd_install_oidc(a):
"""Sign in to the dashboard through an OIDC provider instead of with the API key."""
from .web import oidc
cfg = _service_check()
old_d = cfg.get("dashboard_auth") or {}
say("Dashboard sign-in through OIDC (a client registered with your provider):")
public_url = _check_url("Dashboard URL", _ask(" Dashboard's URL, as browsers reach it", 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")
client_id = _ask(" Client ID (from your provider's client config)", a.client_id,
old_d.get("client_id") or "llm-host", "--client-id")
have_secret = paths.OIDC_SECRET_FILE.exists() and old_d
secret = _ask(" Client secret", None, "keep" if have_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.
@ -565,53 +612,168 @@ def cmd_install_newt(a):
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()
oidc.OIDC(dash, paths.oidc_secret() if secret == "keep" else secret).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}
if secret != "keep":
paths.save_secret(paths.OIDC_SECRET_FILE, secret)
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()
extra = ("\nAuthenticator codes (install-otp) are unused while OIDC is on; they come back with remove-oidc."
if paths.OTP_SECRET_FILE.exists() else "")
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.
Done. The dashboard now signs in through {issuer}; the API key no longer opens it (the API
itself still uses the key).
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""")
Sign-in happens at {public_url}, and visits by any other address are sent there, so the
dashboard has to be reachable at that URL -- see `llmhost expose-dashboard`. If you can't
get in, `llmhost remove-oidc` puts the API key back.{extra}""")
def cmd_remove_newt(a):
"""Back to a LAN-only install: stop newt, and the dashboard takes the API key again."""
def cmd_remove_oidc(a):
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)
had = bool(cfg.pop("dashboard_auth", None))
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.")
after = "the API key" + (" or an authenticator code" if paths.OTP_SECRET_FILE.exists() else "")
say(f"OIDC sign-in is off; the dashboard takes {after} again." if had else "OIDC sign-in wasn't on.")
def _show_pairing(secret):
from . import otp, qr
uri = otp.pairing_uri(secret, default_host())
say("\nScan this with an authenticator app (Google Authenticator, 1Password, Aegis, ...):\n")
for row in qr.QR(uri).terminal():
say(" " + row)
say(f"\nOr enter this key by hand (time-based, 6 digits, 30 s): {otp.grouped(secret)}\n")
def cmd_install_otp(a):
"""Pair authenticator apps; their codes then also open the dashboard."""
from . import otp
cfg = _service_check()
if not sys.stdin.isatty() or not sys.stdout.isatty():
sys.exit("install-otp shows a QR code and asks for a code back, so run it in a terminal")
existing = paths.OTP_SECRET_FILE.exists()
if a.show:
if not existing:
sys.exit("no authenticator is paired yet; run `llmhost install-otp`")
say("This is the existing pairing. Anyone who sees it can make codes, so keep it private.")
_show_pairing(paths.read_secret(paths.OTP_SECRET_FILE, "authenticator secret", "llmhost install-otp"))
say("Add it to as many apps or devices as you like; they all make the same codes.")
return
if existing and input("An authenticator is already paired. Replace it? Apps paired now stop working. "
"(To add another device instead: llmhost install-otp --show) [y/N] ").strip().lower() not in ("y", "yes"):
sys.exit("kept the existing pairing")
secret = otp.new_secret()
_show_pairing(secret)
for attempt in range(3):
code = input("Enter the 6-digit code the app shows, to confirm: ").strip()
if otp.matching_step(secret, code) is not None:
break
say("That code doesn't match. Check the phone's clock is set automatically, then try the current code.")
else:
sys.exit("not paired; nothing was changed")
paths.save_secret(paths.OTP_SECRET_FILE, secret)
cfg.pop("dashboard_key_login", None) # a new pairing starts with the key still working
paths.save_config(cfg)
_restart_if_running("web")
oidc_on = (cfg.get("dashboard_auth") or {}).get("mode") == "oidc"
say("""
Paired. The dashboard's sign-in now also takes a code from the app, alongside the API key.
To add another phone or app later: llmhost install-otp --show. To unpair: llmhost remove-otp."""
+ ("\nOIDC sign-in is on, which takes precedence; codes work once it's removed (remove-oidc)." if oidc_on else ""))
def cmd_remove_otp(a):
cfg = _service_check()
had = paths.OTP_SECRET_FILE.exists()
paths.OTP_SECRET_FILE.unlink(missing_ok=True)
cfg.pop("dashboard_key_login", None) # without codes, the key is the way in again
paths.save_config(cfg)
_restart_if_running("web")
say("Unpaired; the dashboard takes the API key again (apps can delete the llm-host entry)." if had
else "No authenticator was paired.")
def _confirm(question):
if not sys.stdin.isatty():
return False
return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
def cmd_expose_dashboard(a):
"""Walk through publishing the dashboard through newt, once it has a sign-in of its own."""
cfg = _service_check()
if not (cfg.get("newt") and service.installed("newt")):
sys.exit("""The dashboard is published through the newt tunnel, which isn't set up yet.
Run `llmhost install-newt` first, then come back here.""")
d = cfg.get("dashboard_auth") or {}
oidc_on = d.get("mode") == "oidc"
otp_on = paths.OTP_SECRET_FILE.exists()
key_on = cfg.get("dashboard_key_login", True)
if oidc_on:
say(f"Sign-in: OIDC through {d['issuer']} -- good; only allowed accounts get in.")
elif otp_on and not key_on:
say("Sign-in: authenticator codes only -- good; the API key you hand out doesn't open it.")
elif otp_on:
say("""Sign-in: authenticator codes, and still the API key.
Once the dashboard is public, anyone you've given the API key could also use it to stop,
start or switch the model. Turning the key off for the dashboard leaves codes as the only
way in there; the API itself keeps using the key.""")
if a.disable_key_login or _confirm("Turn off API-key sign-in on the dashboard?"):
cfg["dashboard_key_login"] = False
paths.save_config(cfg)
_restart_if_running("web")
key_on = False
say("Done: the dashboard now takes authenticator codes only.")
else:
say("""Sign-in: the API key only.
That's the same key you hand to API users. Once the dashboard is public, any of them --
or anyone the key leaks to -- could stop, start or switch the model. Give the dashboard
its own sign-in first:
llmhost install-oidc sign in through your OIDC provider (recommended)
llmhost install-otp codes from an authenticator app""")
if not (a.force or _confirm("Publish it anyway, behind the API key alone?")):
sys.exit("Not published. Set up a sign-in, then run `llmhost expose-dashboard` again.")
public_url = d.get("public_url") if oidc_on else None
if not public_url:
public_url = _check_url("Dashboard URL", _ask("Public address for the dashboard", a.public_url, None,
"--public-url"))
host = urllib.parse.urlsplit(public_url).netloc
ip = lan_ip()
pangolin_auth = ("off (llm-host signs people in through your OIDC provider; a second login in front would"
" get in the way)" if oidc_on else
"your choice: off, or on as an extra layer in front of llm-host's own sign-in")
say(f"""
In Pangolin, on the same site as the API, add an HTTP resource:
domain {host}
target http://{ip}:{cfg['web_port']} (this machine's LAN address, not localhost)
authentication {pangolin_auth}""")
if oidc_on:
say(f" and make sure your OIDC client allows the redirect URI {public_url}/auth/callback")
if not sys.stdin.isatty():
return
input("\nPress Enter once the resource is saved, to check it from here... ")
try:
with urllib.request.urlopen(public_url + "/auth/config", timeout=15) as r:
got = json.loads(r.read())
ok = got.get("mode") in ("key", "oidc")
except Exception as e:
ok, got = False, e
if ok:
say(f"It works: {public_url} reaches this dashboard.")
else:
say(f"Couldn't reach this dashboard at {public_url} yet ({got}). A new resource's certificate can take a"
f" minute; check the domain, the target and that the resource is enabled, then try the URL in a browser.")
def cmd_download(a):
@ -837,17 +999,29 @@ def main(argv=None):
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 = sub.add_parser("install-newt", help="reach the API from the internet through a Pangolin tunnel (dashboard stays local)")
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)
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt)
s = sub.add_parser("install-oidc", help="sign in to the dashboard through an OIDC provider instead of the API key")
s.add_argument("--public-url", help="the dashboard's 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 (secret: prompted, or $LLMHOST_OIDC_SECRET)")
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed in (repeatable)")
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed in (repeatable)")
s.set_defaults(fn=cmd_install_oidc)
sub.add_parser("remove-oidc", help="undo install-oidc: the dashboard takes the API key again"
).set_defaults(fn=cmd_remove_oidc)
s = sub.add_parser("install-otp", help="pair authenticator apps; their codes also open the dashboard")
s.add_argument("--show", action="store_true", help="show the existing pairing again, to add another device")
s.set_defaults(fn=cmd_install_otp)
sub.add_parser("remove-otp", help="undo install-otp: unpair authenticator apps").set_defaults(fn=cmd_remove_otp)
s = sub.add_parser("expose-dashboard", help="walk through publishing the dashboard through newt (after install-newt and a sign-in)")
s.add_argument("--public-url", help="the dashboard's public address")
s.add_argument("--disable-key-login", action="store_true", help="with authenticator codes set up, stop the API key opening the dashboard")
s.add_argument("--force", action="store_true", help="publish even with only the API key protecting it")
s.set_defaults(fn=cmd_expose_dashboard)
s = sub.add_parser("download", help="download a model ahead of time")
s.add_argument("model")
s.set_defaults(fn=cmd_download)