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

144
README.md
View file

@ -53,8 +53,11 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
| `llmhost logs -f` | follow the model server log (`--web` for the dashboard's, `--newt` for the tunnel's) |
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
| `llmhost key` | print the API key |
| `llmhost install-newt` | optional: reach this server from the internet through a Pangolin tunnel, with OIDC sign-in on the dashboard (see [Reaching it from the internet](#reaching-it-from-the-internet)) |
| `llmhost remove-newt` | undo `install-newt`: back to LAN-only, dashboard back to the API key |
| `llmhost install-newt` | optional: reach the API from the internet through a Pangolin tunnel; the dashboard stays local (see [Reaching it from the internet](#reaching-it-from-the-internet)) |
| `llmhost install-oidc` | optional: sign in to the dashboard through an OIDC provider instead of the API key |
| `llmhost install-otp` | optional: pair authenticator apps; their codes also open the dashboard (`--show` to add another device) |
| `llmhost expose-dashboard` | walk through publishing the dashboard through the tunnel, once it has a sign-in of its own |
| `llmhost remove-newt` / `remove-oidc` / `remove-otp` | undo the matching `install-*` |
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
| `llmhost opencode-config` | print what to add to opencode on another machine |
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
@ -71,52 +74,56 @@ whole duration counts as generation.
## Reaching it from the internet
A plain install is LAN-only, and the dashboard asks for the API key. To let people use it from
anywhere, `llmhost install-newt` adds two things on top:
A plain install is LAN-only, and the dashboard asks for the API key. Going further is a few separate,
optional steps, so the API can go online without the dashboard:
- **A tunnel.** [newt](https://github.com/fosrl/newt) dials out to your [Pangolin](https://github.com/fosrl/pangolin)
server, which serves HTTPS on your domain. Nothing on this machine is opened to the internet, and no port is forwarded.
newt runs as a third user service, in userspace (no root). It's a pinned release, checked against its sha256 before it's installed.
- **OIDC sign-in on the dashboard, replacing the API key there.** Whoever holds the key can also stop or
switch the model from the dashboard, which is too much to hand out with the key. The API itself is
unchanged and still takes the key.
| step | what it adds |
|---|---|
| `llmhost install-newt` | the API, online through a tunnel; the dashboard stays on your LAN |
| `llmhost install-oidc` | dashboard sign-in through your OIDC provider, replacing the API key |
| `llmhost install-otp` | dashboard sign-in with codes from an authenticator app, alongside (or instead of) the key |
| `llmhost expose-dashboard` | a walkthrough for putting the dashboard online too, once it has one of those sign-ins |
You need a Pangolin server with a Newt site (Pangolin: *Sites → Add Site → Newt*, which gives an endpoint, ID and
secret) and an OIDC client registered with your identity provider:
### The API: `install-newt`
- a confidential client using `client_secret_basic`
- the authorization-code flow with PKCE (S256)
- scopes `openid profile email groups`
- the redirect URI `https://<dashboard host>/auth/callback`
[newt](https://github.com/fosrl/newt) dials out to your [Pangolin](https://github.com/fosrl/pangolin) server, which
serves HTTPS on your domain. Nothing on this machine is opened to the internet, and no port is forwarded. newt runs as
a third user service, in userspace (no root). It's a pinned release, checked against its sha256 before it's installed.
Then:
Create a Newt site in Pangolin (*Sites → Add Site → Newt*, which gives an endpoint, ID and secret), then:
```bash
llmhost install-newt \
--endpoint https://pangolin.example.com --newt-id <site id> \
--public-url https://llm-dash.example.com \
--issuer https://auth.example.com --client-id llm-host \
llmhost install-newt --endpoint https://pangolin.example.com --newt-id <site id>
```
It asks for the site secret, or reads `$LLMHOST_NEWT_SECRET`; it's never taken as a flag, so it stays out of shell
history. The secret is stored in `~/.config/llm-host/newt_secret` (mode 600) and handed to newt in its environment
at start, never written into a service file or `config.json`. Running it again changes only what you give it.
Then add one HTTP resource in Pangolin, for the API: a host of your choice → `<this machine's LAN IP>:<API port>`,
with Pangolin's own authentication off, since llm-host checks the API key. Point it at the LAN IP, not
`localhost`, which llm-host treats as local. Clients use `https://<API host>/v1` with the key; for opencode, see
[`opencode-install.sh`](#connecting-opencode).
### Dashboard sign-in: `install-oidc` and `install-otp`
Out of the box the dashboard takes the API key, the same key you hand to API users. That's fine on your LAN, but
anyone holding the key could also stop, start or switch the model from the dashboard. Before the dashboard goes
online, give it a sign-in of its own.
**OIDC** (`llmhost install-oidc`) replaces the key with sign-in through your identity provider, limited to the
groups or usernames you allow. Register a confidential client using `client_secret_basic`, the authorization-code
flow with PKCE (S256), scopes `openid profile email groups`, and the redirect URI `https://<dashboard host>/auth/callback`:
```bash
llmhost install-oidc --public-url https://llm-dash.example.com \
--issuer https://auth.example.com --client-id <client id from the provider> \
--allow-group llm-admins # and/or --allow-user <username>; repeatable
```
It asks for anything left out. The two secrets are always prompted for, or read from `$LLMHOST_NEWT_SECRET` and
`$LLMHOST_OIDC_SECRET`, and never taken as flags, so they stay out of shell history. They're stored in
`~/.config/llm-host/` with mode 600 and handed to the services at start; they're never written into a service
file or `config.json`. Running it again changes only what you give it.
It ends by printing the two Pangolin HTTP resources to create, both pointing at this machine's LAN address (not
`localhost`, which llm-host treats as local), and **with Pangolin's own SSO off**:
| resource | target | who checks |
|---|---|---|
| dashboard, at the `--public-url` host | `<LAN IP>:<web port>` | llm-host, through your OIDC provider |
| API, at a host of your choice | `<LAN IP>:<API port>` | llm-host, with the API key |
Clients then use `https://<API host>/v1` with the key from `llmhost key`, or from the dashboard's **Connect** button.
It shows anyone signed in the key, plus the steps to add this server to opencode: type the API's address and it
fills in a key-saving command and the provider block, both with copy buttons.
For Authelia, the client looks like this:
It asks for the client secret (or reads `$LLMHOST_OIDC_SECRET`) and checks the provider's discovery document.
Sign-in happens at the public URL, and visits by any other address are sent there, so the dashboard must be
reachable at that URL; see `expose-dashboard`. For Authelia, the client looks like this:
```yaml
identity_providers:
@ -136,20 +143,38 @@ identity_providers:
token_endpoint_auth_method: client_secret_basic
```
How the dashboard's sign-in behaves:
How OIDC sign-in behaves:
- **Only listed people get in.** A person must be in an allowed group or have an allowed username
(`preferred_username`, falling back to email). Groups come from userinfo.
- **Sessions are HttpOnly, Secure, `SameSite=Lax` cookies.** They last 12 hours and are held in memory, so
restarting the dashboard signs everyone out. State-changing requests must come from the dashboard's own origin.
- **The ID token is checked.** Its issuer, audience, expiry and nonce must match. It arrives directly from the
token endpoint over TLS, which OIDC allows in place of verifying its signature.
- **Other addresses redirect to the public URL.** A visit to any other name for the machine
(`http://<host>.local:11340`) is sent there, because that's the only host the session cookie exists on.
**Authenticator codes** (`llmhost install-otp`) need no provider. It shows a QR code in the terminal; scan it with
any authenticator app, then type the code it shows to confirm. After that, the dashboard's sign-in also accepts a
current 6-digit code. To add another phone later, `llmhost install-otp --show` shows the same pairing again. Each
code works once, and after 5 wrong codes in 5 minutes codes are refused for a while. The limit is global, because
behind a tunnel every request comes from the same address. Codes are TOTP: SHA-1, 6 digits, 30 seconds, the
defaults every app supports. The secret is kept in `~/.config/llm-host/otp_secret` (mode 600). The API key keeps
working on the dashboard too, until `expose-dashboard` offers to turn it off there.
For both, sessions are HttpOnly, `SameSite=Lax` cookies, Secure behind HTTPS. They last 12 hours and are held in
memory, so restarting the dashboard signs everyone out. State-changing requests must come from the dashboard's own
page. While OIDC is on, it's the only way in, and codes come back with `remove-oidc`.
### The dashboard: `expose-dashboard`
`llmhost expose-dashboard` won't start until `install-newt` is done. It then checks the dashboard's sign-in:
- **OIDC:** fine.
- **Authenticator codes:** it offers to stop the API key opening the dashboard.
- **The key alone:** it explains the risk and asks before going on (`--force` skips the question).
Then it describes the Pangolin resource to add (the dashboard's host → `<LAN IP>:<dashboard port>`) and, once you
press Enter, checks the public URL reaches this dashboard.
`llmhost status` shows the tunnel and sign-in settings. `setup` and `update` keep them, and `update` moves newt to
a newly pinned release. `llmhost remove-newt` undoes it all: it removes the service, the binary and both secrets,
and switches the dashboard back to the key.
a newly pinned release. Each step has an undo: `remove-newt`, `remove-oidc`, `remove-otp`.
## Connecting opencode
@ -166,6 +191,23 @@ A config with comments (`.jsonc`) is never rewritten, since that would drop them
that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (mybox.local)`
— under the provider id `llmhost-<shorthost>`.
**On any machine, in one step**, run `opencode-install.sh` from this repo. It needs only the API's address and
the key, not the dashboard or llm-host, so you can hand it to people who reach just the API, such as through a
tunnel that exposes the API alone. The dashboard's **Connect** button shows the command with the address filled in:
```bash
/bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/opencode-install.sh)" -- --url https://<API host>
```
It checks the server answers with the key, which it asks for without echoing it (or pass `--key` /
`$LLMHOST_API_KEY`, at the cost of the key landing in shell history). Then it installs opencode with the official
installer, unless it's already there, saves the key to `~/.config/opencode/llmhost-<host>.key` (mode 600), and adds
the provider to `opencode.json`. Everything else in that file is kept, and it's backed up as
`opencode.json.before-llmhost` first. It makes the server the default model when you have none; if you do, it asks
first, and `--default` / `--no-default` decide without asking. It also drops any key opencode had cached for that
provider. A `.jsonc` config is never rewritten; the block is printed to paste instead. `--remove` takes the server
back out. It needs `curl` and `python3`.
### One opencode, several servers
The two paths use different provider ids, so a single opencode config can point at a local server and any number
@ -289,7 +331,9 @@ python3 tests/test_opencode.py # or run one directly
| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server |
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
| `tests/test_dashboard_auth.py` | API-key mode, and OIDC sign-in against a fake provider: PKCE, state/nonce/aud/iss/exp checks, allow list, origin check, sign-out |
| `tests/test_newt.py` | `install-newt`/`remove-newt` against fake services: pinned checksum, secrets kept out of config, output and argv, re-runs, undo |
| `tests/test_opencode_install.py` | `opencode-install.sh` against a fake API in a throwaway HOME: new and existing configs, default-model choice, cached-key cleanup, `--remove`, refusals |
| `tests/test_newt.py` | `install-newt`, `install-oidc`, `install-otp`, `expose-dashboard` and their undos against fake services: pinned checksum, secrets kept out of config, output and argv, re-runs |
| `tests/test_otp.py` | TOTP against RFC 6238, code replay and lockout, the QR encoder against reference matrices, code sign-in on the dashboard |
| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update |
## Continuing on an NVIDIA box
@ -334,7 +378,8 @@ suites are hermetic and don't need a GPU), so run that first.
| `~/.local/share/llm-host/` | this repo (`src/`), backend venvs, the assembled CUDA toolkit |
| `~/.config/llm-host/config.json` | the plan: backend, fitting models, active model, ports |
| `~/.config/llm-host/api_key` | API key (mode 600) |
| `~/.config/llm-host/oidc_secret` | dashboard sign-in client secret (mode 600), after `install-newt` |
| `~/.config/llm-host/oidc_secret` | OIDC client secret (mode 600), after `install-oidc` |
| `~/.config/llm-host/otp_secret` | authenticator-app secret (mode 600), after `install-otp` |
| `~/.config/llm-host/newt_secret` | Pangolin site secret (mode 600), after `install-newt` |
| `~/.local/share/llm-host/newt/` | the newt binary, after `install-newt` |
| `~/.cache/huggingface/hub/` | downloaded models |
@ -352,5 +397,6 @@ On macOS the services are launchd agents, so they run while you're logged in.
setting applied instead.
- AMD (ROCm), Intel and CPU-only machines aren't supported yet.
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't forward their ports to the internet;
use [`llmhost install-newt`](#reaching-it-from-the-internet), which puts HTTPS in front and OIDC sign-in on the dashboard.
use [`llmhost install-newt`](#reaching-it-from-the-internet), which puts HTTPS in front, and give the dashboard
its own sign-in before `expose-dashboard`.
- Everyone using the API shares one key, with no per-person revocation or rate limits.

View file

@ -104,7 +104,8 @@ def run_server(cfg, entry, choice, args):
controls = hfcache.template_controls(choice["repo"])
srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls)))
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
reasons=choice.get("reasoning", entry.get("reasoning"))))
proxy.kill_stale(inner, VENV, "mlx_lm")
exe = str(VENV / "bin/mlx_lm.server")

View file

@ -73,10 +73,12 @@ def _uncached(usage):
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None,
upstream_model="default_model", upstream_key=None):
upstream_model="default_model", upstream_key=None, reasons=False):
"""upstream_model: what the inner server calls the loaded model ("default_model" makes
mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent
on to an inner server that checks keys itself (vLLM)."""
on to an inner server that checks keys itself (vLLM). reasons: whether the model
thinks, reported in /v1/models so a client setup (opencode-install.sh) can configure
the model the way `llmhost opencode-config` does."""
# Names a client may call the loaded model: its llm-host name, its repo id, and the
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
@ -121,7 +123,8 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso
return
if self.path.startswith("/v1/models"):
return self._json(200, {"object": "list", "data": [
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context,
"reasoning": bool(reasons)}]})
self._forward("GET", None)
def _model_ok(self, body):

View file

@ -175,7 +175,8 @@ def run_server(cfg, entry, choice, args):
srv = proxy.listen(port, proxy.make_handler(
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
upstream_model=entry["name"], upstream_key=key))
upstream_model=entry["name"], upstream_key=key,
reasons=choice.get("reasoning", entry.get("reasoning"))))
proxy.kill_stale(inner, VENV, "vllm")
exe = str(VENV / "bin/vllm")
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.

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)

104
llmhost/otp.py Normal file
View file

@ -0,0 +1,104 @@
"""One-time codes from an authenticator app (TOTP, RFC 6238), for dashboard sign-in.
`llmhost install-otp` makes a secret, shows it as a QR code to pair the app(s), and once a
code checks out stores it in ~/.config/llm-host/otp_secret (0600). The dashboard then
accepts a current code wherever it asks for the API key. Stdlib only.
The parameters are the ones every authenticator app defaults to -- SHA-1, 6 digits, 30
seconds -- since some apps ignore anything else in the pairing link.
"""
import base64
import hashlib
import hmac
import secrets
import struct
import threading
import time
import urllib.parse
from collections import deque
STEP = 30
DIGITS = 6
WINDOW = 1 # accept the previous and next step too: clocks drift
MAX_FAILURES = 5 # wrong codes allowed in FAIL_WINDOW before codes are refused
FAIL_WINDOW = 300
ISSUER = "llm-host"
def new_secret() -> str:
return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=")
def _key(secret_b32: str) -> bytes:
s = secret_b32.strip().replace(" ", "").upper()
return base64.b32decode(s + "=" * (-len(s) % 8))
def code_at(secret_b32: str, t: float, digits=DIGITS, step=STEP) -> str:
counter = int(t // step)
h = hmac.new(_key(secret_b32), struct.pack(">Q", counter), hashlib.sha1).digest()
o = h[-1] & 0x0F
n = (struct.unpack(">I", h[o:o + 4])[0] & 0x7FFFFFFF) % 10 ** digits
return str(n).zfill(digits)
def pairing_uri(secret_b32: str, account: str) -> str:
label = urllib.parse.quote(f"{ISSUER}:{account}", safe=":@")
q = urllib.parse.urlencode({"secret": secret_b32, "issuer": ISSUER, "algorithm": "SHA1",
"digits": DIGITS, "period": STEP})
return f"otpauth://totp/{label}?{q}"
def grouped(secret_b32: str) -> str:
"""The secret in groups of four, for typing into an app that can't scan."""
return " ".join(secret_b32[i:i + 4] for i in range(0, len(secret_b32), 4))
def matching_step(secret_b32: str, code: str, now=None):
"""The time step `code` belongs to (within the drift window), or None."""
code = "".join(ch for ch in str(code) if ch.isdigit())
if len(code) != DIGITS:
return None
now = time.time() if now is None else now
base = int(now // STEP)
for step in range(base - WINDOW, base + WINDOW + 1):
if hmac.compare_digest(code_at(secret_b32, step * STEP), code):
return step
return None
class Verifier:
"""Checks dashboard sign-in codes: each code works once, and after MAX_FAILURES wrong
ones within FAIL_WINDOW, every code is refused until the window passes. The limit is
global rather than per address because behind a tunnel every request comes from the
same place; at worst a guesser locks codes out for a few minutes, and the API key
still works."""
def __init__(self, secret_b32: str, clock=time.time):
self.secret = secret_b32
self.clock = clock
self.lock = threading.Lock()
self.used_step = None
self.failures = deque()
def locked_for(self) -> int:
now = self.clock()
with self.lock:
while self.failures and now - self.failures[0] > FAIL_WINDOW:
self.failures.popleft()
if len(self.failures) >= MAX_FAILURES:
return int(FAIL_WINDOW - (now - self.failures[0])) + 1
return 0
def check(self, code: str) -> str:
""""ok", "locked" or "wrong"."""
if self.locked_for():
return "locked"
now = self.clock()
step = matching_step(self.secret, code, now)
with self.lock:
if step is not None and (self.used_step is None or step > self.used_step):
self.used_step = step
return "ok"
self.failures.append(now)
return "wrong"

View file

@ -7,8 +7,9 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
~/.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
~/.config/llm-host/oidc_secret dashboard OIDC client secret (0600), after install-oidc
~/.config/llm-host/otp_secret authenticator-app secret (0600), after install-otp
"""
import json
import os
@ -26,6 +27,7 @@ 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"
OTP_SECRET_FILE = CONFIG_DIR / "otp_secret"
NEWT_DIR = DATA / "newt"
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
BIN_DIR = HOME / ".local/bin"
@ -91,4 +93,4 @@ def save_secret(path, secret: str) -> None:
def oidc_secret() -> str:
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-newt")
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-oidc")

254
llmhost/qr.py Normal file
View file

@ -0,0 +1,254 @@
"""A small QR code encoder, for showing an authenticator pairing link in the terminal.
Stdlib only, like the rest of llm-host. Byte mode, error correction level M, versions
1-10 (up to 213 bytes, plenty for an otpauth:// URI). Follows ISO/IEC 18004, laid out
the way Project Nayuki's reference encoder does it.
"""
# Error correction level M, by version (index 0 unused).
ECC_PER_BLOCK = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26]
NUM_BLOCKS = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5]
ALIGN = [[], [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34],
[6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50]]
FORMAT_ECL_M = 0
MAX_VERSION = 10
def _raw_modules(ver):
n = (16 * ver + 128) * ver + 64
if ver >= 2:
k = ver // 7 + 2
n -= (25 * k - 10) * k - 55
if ver >= 7:
n -= 36
return n
def _data_codewords(ver):
return _raw_modules(ver) // 8 - ECC_PER_BLOCK[ver] * NUM_BLOCKS[ver]
def _gf_mul(x, y):
z = 0
for i in reversed(range(8)):
z = (z << 1) ^ ((z >> 7) * 0x11D)
z ^= ((y >> i) & 1) * x
return z
def _rs_divisor(degree):
out = [0] * (degree - 1) + [1]
root = 1
for _ in range(degree):
for j in range(degree):
out[j] = _gf_mul(out[j], root)
if j + 1 < degree:
out[j] ^= out[j + 1]
root = _gf_mul(root, 0x02)
return out
def _rs_remainder(data, divisor):
out = [0] * len(divisor)
for b in data:
factor = b ^ out.pop(0)
out.append(0)
for i, coef in enumerate(divisor):
out[i] ^= _gf_mul(coef, factor)
return out
def _codewords(data: bytes):
for ver in range(1, MAX_VERSION + 1):
count_bits = 8 if ver <= 9 else 16
if 4 + count_bits + 8 * len(data) <= _data_codewords(ver) * 8:
break
else:
raise ValueError(f"too long for a QR code here ({len(data)} bytes)")
bits = []
def put(val, n):
bits.extend((val >> i) & 1 for i in reversed(range(n)))
put(0b0100, 4)
put(len(data), count_bits)
for b in data:
put(b, 8)
cap = _data_codewords(ver) * 8
put(0, min(4, cap - len(bits)))
put(0, -len(bits) % 8)
pad = 0xEC
while len(bits) < cap:
put(pad, 8)
pad ^= 0xEC ^ 0x11
words = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
nblocks, ecl = NUM_BLOCKS[ver], ECC_PER_BLOCK[ver]
raw = _raw_modules(ver) // 8
nshort = nblocks - raw % nblocks
short_len = raw // nblocks
div = _rs_divisor(ecl)
blocks, k = [], 0
for i in range(nblocks):
dlen = short_len - ecl + (0 if i < nshort else 1)
d = words[k:k + dlen]
k += dlen
ecc = _rs_remainder(d, div)
if i < nshort:
d = d + [None]
blocks.append(d + ecc)
out = []
for i in range(len(blocks[0])):
for blk in blocks:
if blk[i] is not None:
out.append(blk[i])
return ver, out
class QR:
def __init__(self, data, mask=None):
if isinstance(data, str):
data = data.encode("utf-8")
self.version, words = _codewords(data)
self.size = n = self.version * 4 + 17
self.m = [[False] * n for _ in range(n)]
self.fn = [[False] * n for _ in range(n)]
self._function_patterns()
self._place(words)
if mask is None:
mask = min(range(8), key=self._penalty_with)
self.mask = mask
self._apply_mask(mask)
self._format_bits(mask)
def _set(self, x, y, dark):
self.m[y][x] = dark
self.fn[y][x] = True
def _function_patterns(self):
n = self.size
for i in range(n):
self._set(6, i, i % 2 == 0)
self._set(i, 6, i % 2 == 0)
for cx, cy in ((3, 3), (n - 4, 3), (3, n - 4)):
for dy in range(-4, 5):
for dx in range(-4, 5):
x, y = cx + dx, cy + dy
if 0 <= x < n and 0 <= y < n:
self._set(x, y, max(abs(dx), abs(dy)) not in (2, 4))
pos = ALIGN[self.version]
last = len(pos) - 1
for i, ax in enumerate(pos):
for j, ay in enumerate(pos):
if (i, j) in ((0, 0), (0, last), (last, 0)):
continue
for dy in range(-2, 3):
for dx in range(-2, 3):
self._set(ax + dx, ay + dy, max(abs(dx), abs(dy)) != 1)
self._format_bits(0) # reserve the area; redrawn after masking
if self.version >= 7:
rem = self.version
for _ in range(12):
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
bits = self.version << 12 | rem
for i in range(18):
bit = (bits >> i) & 1 == 1
a, b = n - 11 + i % 3, i // 3
self._set(a, b, bit)
self._set(b, a, bit)
def _format_bits(self, mask):
data = FORMAT_ECL_M << 3 | mask
rem = data
for _ in range(10):
rem = (rem << 1) ^ ((rem >> 9) * 0x537)
bits = (data << 10 | rem) ^ 0x5412
bit = lambda i: (bits >> i) & 1 == 1
n = self.size
for i in range(6):
self._set(8, i, bit(i))
self._set(8, 7, bit(6))
self._set(8, 8, bit(7))
self._set(7, 8, bit(8))
for i in range(9, 15):
self._set(14 - i, 8, bit(i))
for i in range(8):
self._set(n - 1 - i, 8, bit(i))
for i in range(8, 15):
self._set(8, n - 15 + i, bit(i))
self._set(8, n - 8, True)
def _place(self, words):
n, i, total = self.size, 0, len(words) * 8
right = n - 1
while right >= 1:
if right == 6:
right = 5
for vert in range(n):
for j in range(2):
x = right - j
upward = ((right + 1) & 2) == 0
y = n - 1 - vert if upward else vert
if not self.fn[y][x] and i < total:
self.m[y][x] = (words[i >> 3] >> (7 - (i & 7))) & 1 == 1
i += 1
right -= 2
@staticmethod
def _mask_bit(mask, x, y):
return [
(x + y) % 2 == 0, y % 2 == 0, x % 3 == 0, (x + y) % 3 == 0,
(x // 3 + y // 2) % 2 == 0, x * y % 2 + x * y % 3 == 0,
(x * y % 2 + x * y % 3) % 2 == 0, ((x + y) % 2 + x * y % 3) % 2 == 0,
][mask]
def _apply_mask(self, mask):
for y in range(self.size):
for x in range(self.size):
if not self.fn[y][x] and self._mask_bit(mask, x, y):
self.m[y][x] = not self.m[y][x]
def _penalty_with(self, mask):
self._apply_mask(mask)
self._format_bits(mask)
p = self._penalty()
self._apply_mask(mask) # XOR again to undo
return p
def _penalty(self):
n, m, p = self.size, self.m, 0
lines = m + [[m[y][x] for y in range(n)] for x in range(n)]
finder_a = [True, False, True, True, True, False, True, False, False, False, False]
finder_b = finder_a[::-1]
for line in lines:
run = 1
for i in range(1, n + 1):
if i < n and line[i] == line[i - 1]:
run += 1
else:
if run >= 5:
p += 3 + run - 5
run = 1
for i in range(n - 10):
seg = line[i:i + 11]
if seg == finder_a or seg == finder_b:
p += 40
for y in range(n - 1):
for x in range(n - 1):
if m[y][x] == m[y][x + 1] == m[y + 1][x] == m[y + 1][x + 1]:
p += 3
dark = sum(sum(row) for row in m)
p += (abs(dark * 20 - n * n * 10) // (n * n)) * 10
return p
def terminal(self, quiet=2):
"""Rows of text, two modules per character, drawn in explicit black on white so
it scans the same on a dark or a light terminal theme."""
n = self.size
dark = lambda x, y: 0 <= x < n and 0 <= y < n and self.m[y][x]
rows = []
for y in range(-quiet, n + quiet, 2):
line = []
for x in range(-quiet, n + quiet):
top, bot = dark(x, y), dark(x, y + 1)
line.append(f"\033[{30 if top else 97};{40 if bot else 107}m▀")
rows.append("".join(line) + "\033[0m")
return rows

View file

@ -171,6 +171,9 @@ pre {
.dialog .snip button { position: absolute; top: 6px; right: 6px; }
#cx-keycmd { white-space: pre-wrap; overflow-wrap: anywhere; }
.dialog .actions { display: flex; justify-content: flex-end; }
.dialog details.manual { margin-bottom: 12px; font-size: 13px; }
.dialog details.manual summary { cursor: pointer; color: var(--muted); margin-bottom: 8px; }
#cx-install { white-space: pre-wrap; overflow-wrap: anywhere; }
.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg);
padding: 8px 14px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; }
.toast.show { opacity: 1; }
@ -278,9 +281,16 @@ pre {
<div class="overlay" id="auth">
<form class="dialog" id="auth-form">
<h3>API key</h3>
<p>Enter the API key from <code>~/.config/llm-host/api_key</code> on the server (or run <code>llmhost key</code>). It's kept in this browser only.</p>
<input id="auth-key" type="password" autocomplete="current-password" placeholder="sk-…" required>
<h3>Sign in</h3>
<div id="auth-key-part">
<p>Enter the API key from <code>~/.config/llm-host/api_key</code> on the server (or run <code>llmhost key</code>). It's kept in this browser only.</p>
<input id="auth-key" type="password" autocomplete="current-password" placeholder="sk-…" aria-label="API key">
</div>
<div id="auth-otp-part" hidden>
<p id="auth-otp-text">Or a code from your authenticator app:</p>
<input id="auth-code" inputmode="numeric" autocomplete="one-time-code" maxlength="7" placeholder="123456"
aria-label="Authenticator code">
</div>
<div class="err" id="auth-err"></div>
<button class="primary" type="submit">Continue</button>
</form>
@ -298,10 +308,16 @@ pre {
<div class="keyrow"><input id="cx-key" type="password" readonly autocomplete="off" aria-label="API key"><button id="cx-show">Show</button><button id="cx-copy">Copy</button></div>
<h4>Add to opencode</h4>
<p>The API's address, as the machine running opencode reaches it:</p>
<div class="keyrow"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
placeholder="https://llm-api.example.com" aria-label="API base URL"></div>
<p>Then run this there, or send it to whoever you're giving access, with the key. It needs only the API, not this
dashboard: it installs opencode if it's missing, asks for the key (hidden), saves it, and adds this server to
<code>opencode.json</code>, keeping their other settings:</p>
<div class="snip" style="margin-bottom:14px"><pre id="cx-install"></pre><button class="small" data-copy="cx-install">Copy</button></div>
<details class="manual">
<summary>Or set it up by hand</summary>
<ol>
<li>The API's address, as this machine reaches it:
<div class="keyrow" style="margin:6px 0 0"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
placeholder="https://llm-api.example.com/v1" aria-label="API base URL"></div></li>
<li>Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
<div class="snip"><pre id="cx-keycmd"></pre><button class="small" data-copy="cx-keycmd">Copy</button></div></li>
<li>Put this in <code>~/.config/opencode/opencode.json</code>. If the file is empty or missing, paste the whole thing;
@ -310,6 +326,7 @@ pre {
<div class="snip"><pre id="cx-block"></pre><button class="small" data-copy="cx-block">Copy</button></div></li>
<li>Pick <b id="cx-pick"></b> in opencode's model list.</li>
</ol>
</details>
<div class="actions"><button id="cx-close">Close</button></div>
</div>
</div>
@ -335,9 +352,14 @@ function toast(msg) {
async function api(path, opts = {}) {
const headers = { "Content-Type": "application/json" };
if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY;
const useKey = AUTH.mode === "key" && KEY && AUTH.key !== false;
if (useKey) 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"); }
if (r.status === 401) {
if (useKey) showAuth("That key was rejected.");
else { AUTH.user = null; $("whoami").hidden = true; showAuth(""); }
throw new Error("unauthorized");
}
const body = await r.json();
if (!r.ok) throw new Error(body.error || r.statusText);
return body;
@ -349,12 +371,38 @@ function showAuth(err = "") {
$("auth").classList.add("show"); $("auth-oidc-go").focus();
return;
}
$("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus();
// Key mode: the API key (unless it's switched off for the dashboard) and, after
// `llmhost install-otp`, a code from an authenticator app.
const keyOn = AUTH.key !== false;
$("auth-key-part").hidden = !keyOn;
$("auth-otp-part").hidden = !AUTH.otp;
$("auth-otp-text").textContent = keyOn ? "Or a code from your authenticator app:" : "Enter a code from your authenticator app:";
$("auth-err").textContent = err; $("auth").classList.add("show");
(keyOn ? $("auth-key") : $("auth-code")).focus();
}
$("auth-form").addEventListener("submit", (e) => {
function signedIn(user, name) {
AUTH.user = user; AUTH.name = name;
$("whoami").textContent = name || user; $("whoami").hidden = !user;
}
$("auth-form").addEventListener("submit", async (e) => {
e.preventDefault();
KEY = $("auth-key").value.trim();
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
const code = AUTH.otp ? $("auth-code").value.replace(/\D/g, "") : "";
if (code) {
let r, body = {};
try {
r = await fetch("/auth/otp", { method: "POST", credentials: "same-origin",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }) });
body = await r.json();
} catch (err) { $("auth-err").textContent = "Couldn't reach the dashboard."; return; }
$("auth-code").value = "";
if (!r.ok) { $("auth-err").textContent = body.error || "That code didn't work."; return; }
signedIn("authenticator", "Authenticator app");
} else {
const k = $("auth-key").value.trim();
if (!k || AUTH.key === false) { $("auth-err").textContent = AUTH.otp ? "Enter a code from your authenticator app." : "Enter the API key."; return; }
KEY = k;
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
}
$("auth").classList.remove("show");
poll();
});
@ -402,6 +450,9 @@ function renderOpencode() {
// One line: pasted as two, the first line's `read` would swallow the second as the key.
`mkdir -p ~/.config/opencode && printf 'API key: ' && stty -echo && read -r k; stty echo; echo; ` +
`[ -n "$k" ] && (umask 077 && printf '%s\\n' "$k" > ${keyfile}) && echo "saved ${keyfile}"; unset k`;
$("cx-install").textContent = url
? `/bin/bash -c "$(curl -fsSL ${CONNECT.installer})" -- --url ${url.replace(/\/v1$/, "")}`
: "Type the API's address above first.";
$("cx-pick").textContent = `${block.name} → ${Object.values(block.models)[0]?.name || CONNECT.model}`;
try { localStorage.setItem("llmhost-api-url", $("cx-url").value.trim()); } catch (e) {}
}
@ -438,7 +489,9 @@ $("logout").onclick = async () => {
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); closeConnect(); showAuth();
return;
}
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; closeConnect(); showAuth();
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null;
if (AUTH.user) { try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {} }
signedIn(null); clearTimeout(pollTimer); closeConnect(); showAuth();
};
const fmt = {
@ -829,10 +882,10 @@ $("logs").addEventListener("toggle", () => {
let pollTimer = null;
async function poll() {
clearTimeout(pollTimer);
if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; }
if (AUTH.mode === "key" ? !(KEY && AUTH.key !== false) && !AUTH.user : !AUTH.user) { showAuth(); return; }
try { render(await api("/api/status")); }
catch (e) {
if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in
if (e.message === "unauthorized" && !(AUTH.mode === "key" && KEY)) return; // session over; wait for sign-in
if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; }
}
pollTimer = setTimeout(poll, 2000);
@ -843,10 +896,8 @@ async function poll() {
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; }
}
if (AUTH.mode === "oidc" || AUTH.otp) $("logout").title = "Sign out of this dashboard";
if (AUTH.user) signedIn(AUTH.user, AUTH.name);
poll();
})();
</script>

View file

@ -28,9 +28,10 @@ import urllib.error
import urllib.parse
import urllib.request
SESSION_COOKIE = "llmhost_session"
from .sessions import SESSION_COOKIE, SESSION_TTL, Sessions, parse_cookies # noqa: F401 (re-exported)
from .sessions import cookie as make_cookie
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
@ -53,15 +54,6 @@ def jwt_claims(token: str) -> dict:
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()
@ -83,7 +75,8 @@ class OIDC:
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.store = Sessions()
self.sessions = self.store.items # sha256(session id) -> {user, name, exp}
self._disco = None
# -- provider ---------------------------------------------------------------------
@ -191,36 +184,16 @@ class OIDC:
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}
sid = self.store.create(user, info.get("name") or user)
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
return self.store.get(cookie_header)
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)
self.store.end(cookie_header)
def same_origin(self, headers) -> bool:
"""For state-changing requests: the browser's Origin (or Referer) must be the
@ -230,7 +203,4 @@ class OIDC:
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)
return make_cookie(name, value, max_age, self.secure, path)

View file

@ -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()

65
llmhost/web/sessions.py Normal file
View file

@ -0,0 +1,65 @@
"""Signed-in dashboard sessions, for OIDC and authenticator-code sign-in. Stdlib only.
A session is a random id in an HttpOnly, SameSite=Lax cookie; only its SHA-256 is kept,
in memory, so a dashboard restart signs everyone out.
"""
import hashlib
import secrets
import threading
import time
SESSION_COOKIE = "llmhost_session"
SESSION_TTL = 12 * 3600
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 cookie(name, value, max_age, secure, path="/"):
attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"]
if secure:
attrs.append("Secure")
return "; ".join(attrs)
class Sessions:
def __init__(self, ttl=SESSION_TTL):
self.ttl = ttl
self.lock = threading.Lock()
self.items = {} # sha256(id) -> {user, name, exp}
@staticmethod
def _h(sid: str) -> str:
return hashlib.sha256(sid.encode()).hexdigest()
def create(self, user, name=None) -> str:
sid = secrets.token_urlsafe(32)
now = time.time()
with self.lock:
for h in [h for h, s in self.items.items() if s["exp"] < now]:
del self.items[h]
self.items[self._h(sid)] = {"user": user, "name": name or user, "exp": now + self.ttl}
return sid
def get(self, cookie_header: str):
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
if not sid:
return None
with self.lock:
s = self.items.get(self._h(sid))
if s and s["exp"] < time.time():
del self.items[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.items.pop(self._h(sid), None)

312
opencode-install.sh Executable file
View file

@ -0,0 +1,312 @@
#!/bin/bash
# Connect opencode to an llm-host server -- installing opencode first if it isn't there.
#
# /bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/opencode-install.sh)" \
# -- --url https://llm-api.example.com
#
# It needs only the API's address and key: not llm-host, and not its dashboard.
#
# It asks for the API key (hidden). To pass it instead, use --key or $LLMHOST_API_KEY;
# note that a key given on the command line ends up in your shell history.
#
# What it does, all in your home directory (no sudo):
# 1. checks the server answers with that key
# 2. installs opencode with the official installer, unless it's already installed
# 3. saves the key to ~/.config/opencode/llmhost-<host>.key (mode 600)
# 4. adds an llmhost-<host> provider to ~/.config/opencode/opencode.json, keeping
# everything else in it (backed up first as opencode.json.before-llmhost), and
# makes it the default model if you have none (or say so)
# 5. drops any key opencode cached for that provider, so the key file is what it uses
#
# Options:
# --url URL the API's address (https://host or https://host/v1)
# --key KEY the API key (default: $LLMHOST_API_KEY, else asked for)
# --default make it opencode's default model without asking
# --no-default leave opencode's default model alone
# --skip-install don't install opencode, only configure it
# --remove take this server back out of opencode's config
# Written for bash 3.2 so it runs on stock macOS.
set -euo pipefail
if [ -t 1 ]; then B=$'\033[1m'; R=$'\033[31m'; Y=$'\033[33m'; G=$'\033[32m'; N=$'\033[0m'; else B=""; R=""; Y=""; G=""; N=""; fi
say() { printf '%s==>%s %s\n' "$B" "$N" "$*"; }
warn() { printf '%sWarning:%s %s\n' "$Y" "$N" "$*" >&2; }
die() { printf '%sError:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }
usage() {
cat <<'EOF'
Connect opencode to an llm-host server, installing opencode first if needed.
opencode-install.sh --url https://llm-api.example.com [options]
--url URL the API's address (https://host or https://host/v1)
--key KEY the API key (default: $LLMHOST_API_KEY, else asked for, hidden)
--default make it opencode's default model without asking
--no-default leave opencode's default model alone
--skip-install don't install opencode, only configure it
--remove take this server back out of opencode's config
EOF
}
[ "${1:-}" = "--" ] && shift
URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0
while [ $# -gt 0 ]; do
case "$1" in
--url) URL="${2:-}"; shift 2 ;;
--url=*) URL="${1#*=}"; shift ;;
--key) KEY="${2:-}"; shift 2 ;;
--key=*) KEY="${1#*=}"; shift ;;
--default) DEFAULT="yes"; shift ;;
--no-default) DEFAULT="no"; shift ;;
--skip-install) INSTALL=0; shift ;;
--remove) REMOVE=1; shift ;;
-h|--help) usage; exit 0 ;;
*) die "unknown option: $1 (see --help)" ;;
esac
done
# A terminal to ask on, even when this script arrived on stdin.
TTY=""
if [ -r /dev/tty ] && [ -w /dev/tty ] && (: </dev/tty) 2>/dev/null; then TTY=/dev/tty; fi
if [ -z "$URL" ]; then
[ -n "$TTY" ] || die "--url is required"
printf 'API address (e.g. https://llm-api.example.com): ' >"$TTY"; read -r URL <"$TTY"
fi
URL="${URL%/}"
case "$URL" in
https://*|http://*) ;;
*) die "--url should start with https:// (got '$URL')" ;;
esac
case "$URL" in */v1) ;; *) URL="$URL/v1" ;; esac
HOST="$(printf '%s' "$URL" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')"
SHORT="$(printf '%s' "${HOST%%.*}" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9-\n' '-')"
PROV="llmhost-$SHORT"
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
CONF="$CONF_DIR/opencode.json"
KEYFILE="$CONF_DIR/$PROV.key"
AUTH="${XDG_DATA_HOME:-$HOME/.local/share}/opencode/auth.json"
# JSON edits need Python. On a Mac without the command line tools, /usr/bin/python3 is
# only a stub that pops up an installer, so don't call it there.
PY=""
if [ "$(uname -s)" = Darwin ] && [ "$(command -v python3 || true)" = /usr/bin/python3 ] \
&& ! xcode-select -p >/dev/null 2>&1; then
PY=""
elif command -v python3 >/dev/null 2>&1; then
PY="$(command -v python3)"
fi
# ---- remove --------------------------------------------------------------------------
if [ "$REMOVE" = 1 ]; then
[ -n "$PY" ] || die "python3 is needed to edit $CONF; remove the \"$PROV\" provider from it by hand"
"$PY" - "$CONF" "$PROV" "$AUTH" <<'PYEOF'
import json, os, sys
conf, prov, auth = sys.argv[1:4]
try:
c = json.load(open(conf))
except (OSError, ValueError):
c = None
if isinstance(c, dict) and prov in (c.get("provider") or {}):
del c["provider"][prov]
if not c["provider"]:
del c["provider"]
if str(c.get("model", "")).startswith(prov + "/"):
del c["model"]
print(f"opencode's default model was {prov}; pick another with /models.")
tmp = conf + ".tmp"
with open(tmp, "w") as f:
json.dump(c, f, indent=2); f.write("\n")
os.replace(tmp, conf)
print(f"Removed the {prov} provider from {conf}.")
else:
print(f"No {prov} provider in {conf}.")
try:
a = json.load(open(auth))
if prov in a:
del a[prov]
json.dump(a, open(auth, "w"), indent=2)
except (OSError, ValueError):
pass
PYEOF
rm -f "$KEYFILE"
say "Done. opencode itself is still installed."
exit 0
fi
# ---- the key, checked against the server ---------------------------------------------
if [ -z "$KEY" ]; then
[ -n "$TTY" ] || die "no API key: pass --key or set \$LLMHOST_API_KEY"
printf 'API key (hidden): ' >"$TTY"
stty -echo <"$TTY" 2>/dev/null || true
read -r KEY <"$TTY" || true
stty echo <"$TTY" 2>/dev/null || true
printf '\n' >"$TTY"
fi
KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
[ -n "$KEY" ] || die "no API key given"
say "Checking $URL"
TMP="$(mktemp)"; trap 'rm -f "$TMP"' EXIT
# The key goes to curl on stdin (as a header file), not on its command line.
CODE="$(printf 'Authorization: Bearer %s\n' "$KEY" | curl -sS -o "$TMP" -w '%{http_code}' \
--max-time 20 -H @- "$URL/models" 2>/dev/null || true)"
case "$CODE" in
200) ;;
401|403) die "the server rejected that API key" ;;
000|"") die "couldn't reach $URL" ;;
*) die "$URL/models answered HTTP $CODE; is that the llm-host API address?" ;;
esac
CTX=32768; REASONS=0
if [ -n "$PY" ]; then
read -r CTX REASONS <<EOF
$("$PY" -c 'import json,sys
d=(json.load(open(sys.argv[1])).get("data") or [{}])[0]
print(int(d.get("max_model_len") or 32768), 1 if d.get("reasoning") else 0)' "$TMP" 2>/dev/null || echo "32768 0")
EOF
fi
say "Server OK"
# ---- opencode ------------------------------------------------------------------------
OC="$(command -v opencode || true)"
[ -n "$OC" ] || { [ -x "$HOME/.opencode/bin/opencode" ] && OC="$HOME/.opencode/bin/opencode"; } || true
if [ -z "$OC" ]; then
if [ "$INSTALL" = 1 ]; then
say "Installing opencode (official installer)"
curl -fsSL https://opencode.ai/install | bash
OC="$HOME/.opencode/bin/opencode"
[ -x "$OC" ] || OC="$(command -v opencode || true)"
[ -n "$OC" ] || die "opencode didn't install; see the output above"
else
warn "opencode isn't installed; configuring it anyway (--skip-install)"
fi
else
say "opencode is already installed ($OC)"
fi
# ---- key file ------------------------------------------------------------------------
mkdir -p "$CONF_DIR"
( umask 077; printf '%s\n' "$KEY" >"$KEYFILE" )
chmod 600 "$KEYFILE"
say "Saved the key to $KEYFILE"
# ---- opencode.json -------------------------------------------------------------------
print_block() {
cat <<EOF
Add this provider to $1 by hand, under "provider", and set "model" if you want it as the default:
"$PROV": {
"npm": "@ai-sdk/openai-compatible",
"name": "LLMHost ($HOST)",
"options": { "baseURL": "$URL", "apiKey": "{file:$KEYFILE}" },
"models": { "default": { "name": "Default model ($HOST)", "tool_call": true,
"limit": { "context": $CTX, "output": $(( CTX / 2 < 65536 ? CTX / 2 : 65536 )) } } }
}
"model": "$PROV/default"
EOF
}
if [ -z "$PY" ]; then
warn "python3 isn't available, so opencode.json can't be edited automatically."
print_block "$CONF"; exit 0
fi
if [ ! -f "$CONF" ] && [ -f "$CONF_DIR/opencode.jsonc" ]; then
warn "$CONF_DIR/opencode.jsonc has comments that an automatic edit would lose."
print_block "$CONF_DIR/opencode.jsonc"; exit 0
fi
CURRENT_MODEL="$("$PY" -c 'import json,sys
try: print(json.load(open(sys.argv[1])).get("model") or "")
except Exception: print("")' "$CONF")"
SET_DEFAULT=0
case "$DEFAULT" in
yes) SET_DEFAULT=1 ;;
no) SET_DEFAULT=0 ;;
ask)
if [ -z "$CURRENT_MODEL" ] || [ "${CURRENT_MODEL#$PROV/}" != "$CURRENT_MODEL" ]; then
SET_DEFAULT=1
elif [ -n "$TTY" ]; then
printf 'opencode currently starts on %s. Switch its default to this server? [y/N] ' "$CURRENT_MODEL" >"$TTY"
read -r ans <"$TTY" || ans=""
case "$ans" in y|Y|yes|YES) SET_DEFAULT=1 ;; esac
fi ;;
esac
"$PY" - "$CONF" "$PROV" "$HOST" "$URL" "$KEYFILE" "$CTX" "$REASONS" "$SET_DEFAULT" "$AUTH" <<'PYEOF'
import json, os, shutil, sys
conf, prov, host, url, keyfile, ctx, reasons, set_default, auth = sys.argv[1:10]
ctx = int(ctx)
c = {}
if os.path.exists(conf) and os.path.getsize(conf) > 0:
try:
c = json.load(open(conf))
except ValueError as e:
sys.exit(f"Error: {conf} isn't valid JSON ({e}); fix it, or move it aside and run this again")
if not isinstance(c, dict):
sys.exit(f"Error: {conf} isn't a JSON object")
backup = conf + ".before-llmhost"
if not os.path.exists(backup):
shutil.copy2(conf, backup)
print(f"Backed up {conf} to {backup}")
# The same entry as `llmhost opencode-config`: one model, `default`, which the server
# answers to whatever is loaded; and, for a thinking model, opencode's own effort menu
# switched off, since the effort is set on the dashboard and the server drops a client's.
entry = {"name": f"Default model ({host})", "tool_call": True,
"limit": {"context": ctx, "output": min(65536, ctx // 2)}}
if reasons == "1":
entry["reasoning"] = True
entry["variants"] = {lvl: {"disabled": True} for lvl in ("low", "medium", "high")}
c.setdefault("$schema", "https://opencode.ai/config.json")
c.setdefault("provider", {})[prov] = {
"npm": "@ai-sdk/openai-compatible",
"name": f"LLMHost ({host})",
"options": {"baseURL": url, "apiKey": "{file:" + keyfile + "}"},
"models": {"default": entry},
}
if set_default == "1":
c["model"] = f"{prov}/default"
os.makedirs(os.path.dirname(conf), exist_ok=True)
tmp = conf + ".tmp"
with open(tmp, "w") as f:
json.dump(c, f, indent=2); f.write("\n")
os.replace(tmp, conf)
print(f"Added the {prov} provider to {conf}" + (" and made it the default model" if set_default == "1" else ""))
# opencode caches a key it was given interactively, and that copy wins over the config;
# drop it so the key file is what's used.
try:
a = json.load(open(auth))
if prov in a:
del a[prov]
tmp = auth + ".tmp"
with open(tmp, "w") as f:
json.dump(a, f, indent=2)
os.chmod(tmp, 0o600)
os.replace(tmp, auth)
print(f"Dropped the key opencode had cached for {prov}")
except (OSError, ValueError):
pass
PYEOF
# ---- check ---------------------------------------------------------------------------
if [ -n "$OC" ] && "$OC" models 2>/dev/null | grep -q "^$PROV/default\$"; then
say "${G}opencode sees $PROV/default${N}"
elif [ -n "$OC" ]; then
warn "opencode doesn't list $PROV/default yet; check $CONF"
fi
echo
say "Done. Start opencode -- it shows the server as \"LLMHost ($HOST)\"."
if [ "$SET_DEFAULT" != 1 ]; then
echo " Your default model is unchanged; pick \"LLMHost ($HOST)\" with /models."
fi
case ":$PATH:" in
*":$HOME/.opencode/bin:"*) ;;
*) if [ "$OC" = "$HOME/.opencode/bin/opencode" ]; then
echo " Open a new terminal first (or run: export PATH=\$HOME/.opencode/bin:\$PATH)."
fi ;;
esac
echo " To take it out again: rerun this with --remove."

1
tests/fixtures/qr_golden.json vendored Normal file

File diff suppressed because one or more lines are too long

View file

@ -40,7 +40,7 @@ def guard(paths, root):
paths.BIN_DIR = Path(root) / ".local/bin"
paths.SHIM = paths.BIN_DIR / "llmhost"
paths.LOG_DIR = Path(root) / "logs"
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "NEWT_DIR", "BIN_DIR", "SHIM", "LOG_DIR"):
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "OTP_SECRET_FILE", "NEWT_DIR", "BIN_DIR", "SHIM", "LOG_DIR"):
value = str(getattr(paths, name))
if not value.startswith(root):
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")

View file

@ -109,6 +109,14 @@ check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk
check("opencode block offers the one alias", list(blk["models"]) == [cx["model"]] == ["default"], blk["models"])
check("opencode block leaves the address to the page", "LABEL" in blk["name"] and "HOST" in blk["options"]["baseURL"], blk)
check("the key isn't inlined in the block", KEY not in json.dumps(blk))
check("installer URL is a raw file in the repo", cx["installer"].startswith("https://")
and cx["installer"].endswith("/opencode-install.sh"), cx["installer"])
R = web.raw_file_url
check("raw URL for a Gitea/Forgejo repo", R("https://git.example.com/pub/llm-host.git", "main", "f.sh")
== "https://git.example.com/pub/llm-host/raw/branch/main/f.sh")
check("raw URL for a GitHub repo", R("https://github.com/someone/llm-host", "dev", "f.sh")
== "https://raw.githubusercontent.com/someone/llm-host/dev/f.sh")
check("no raw URL for an ssh remote", R("git@github.com:someone/llm-host.git", "main", "f.sh") is None)
srv.shutdown()
print("\n2. OIDC mode refuses the key and unsigned visitors")
@ -120,6 +128,7 @@ srv = serve(o)
st, _, body, _ = req(srv, "GET", "/auth/config", PUB_HOST)
check("config reports oidc, nobody signed in", json.loads(body) == {"mode": "oidc", "user": None, "name": None}, body)
check("status without session -> 401", req(srv, "GET", "/api/status", PUB_HOST)[0] == 401)
check("the dashboard doesn't serve the opencode installer", req(srv, "GET", "/opencode-install.sh", PUB_HOST)[0] == 404)
check("the API key no longer opens it", req(srv, "GET", "/api/status", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
st, h, _, _ = req(srv, "GET", "/", {"Host": "mybox.local:11340"})
check("a LAN name is sent to the public URL", st == 302 and h["location"] == PUBLIC + "/", h.get("location"))

View file

@ -1,17 +1,20 @@
"""install-newt / remove-newt: pinned download, secrets kept out of config and output,
OIDC switched on with the tunnel and off again, all against fake services."""
"""The internet upgrades, against fake services: install-newt (API only, pinned download,
secrets kept out of config/output/argv), install-oidc, install-otp, expose-dashboard, and
their remove-* undo commands."""
import contextlib
import hashlib
import io
import json
import os
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import cli, newt, paths, service
from llmhost import cli, newt, otp, paths, service
from llmhost.web import oidc
harness.guard(paths, ROOT)
@ -38,16 +41,22 @@ newt._fetch = lambda url: (fetches.append(url), FAKE_BIN)[1]
oidc.OIDC._http = staticmethod(lambda m, url, data=None, headers=None: (200, json.dumps({
"issuer": ISSUER, "authorization_endpoint": ISSUER + "/a", "token_endpoint": ISSUER + "/t"}).encode()))
sys.stdin = io.StringIO() # no terminal: missing values are errors, not prompts
class TTY(io.StringIO):
def isatty(self):
return True
def run(argv, env=None):
import os
def run(argv, env=None, tty_input=None):
"""Run the CLI. Without tty_input there's no terminal (missing values are errors, not
prompts); with it, stdin/stdout are a terminal and input() reads those lines."""
saved = {k: os.environ.get(k) for k in ("LLMHOST_NEWT_SECRET", "LLMHOST_OIDC_SECRET")}
for k in saved:
os.environ.pop(k, None)
os.environ.update(env or {})
out, code = io.StringIO(), 0
out, code = (TTY() if tty_input is not None else io.StringIO()), 0
old_in = sys.stdin
sys.stdin = TTY("".join(l + "\n" for l in tty_input)) if tty_input is not None else io.StringIO()
try:
with contextlib.redirect_stdout(out):
cli.main(argv)
@ -56,6 +65,7 @@ def run(argv, env=None):
if isinstance(e.code, str):
out.write(e.code)
finally:
sys.stdin = old_in
for k, v in saved.items():
os.environ.pop(k, None)
if v is not None:
@ -67,9 +77,9 @@ cfg = harness.config()
paths.save_config(cfg)
paths.api_key(create=True)
ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123",
"--public-url", "https://dash.example.test", "--issuer", ISSUER, "--allow-group", "llm-admins"]
SECRETS = {"LLMHOST_NEWT_SECRET": NEWT_SECRET, "LLMHOST_OIDC_SECRET": OIDC_SECRET}
NEWT_ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123"]
OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER,
"--client-id", "client-from-provider", "--allow-group", "llm-admins"]
print("\n1. a plain install doesn't include newt")
check("setup's services are model and web only", service.NAMES == ("model", "web"), service.NAMES)
@ -87,76 +97,121 @@ check("nothing installed after a bad checksum", not newt.binary().exists())
newt.SHA256 = real
check("good checksum installs", newt.ensure_binary(lambda *_: None) is True)
check("binary is executable", newt.binary().stat().st_mode & 0o111)
check("version recorded", newt.installed_version() == newt.VERSION)
check("second call is a no-op", newt.ensure_binary(lambda *_: None) is False)
check("download URL is the pinned GitHub release",
fetches[-1].startswith(f"https://github.com/fosrl/newt/releases/download/{newt.VERSION}/newt_"), fetches)
print("\n3. install-newt needs everything, without a terminal")
code, out = run(ARGS)
check("missing secrets -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out)
code, out = run([a for a in ARGS if a not in ("--allow-group", "llm-admins")], SECRETS)
check("no allow list -> error", code != 0 and "allow" in out, out)
code, out = run([*ARGS[:6], "http://dash.example.test", *ARGS[7:]], SECRETS)
check("an http:// public URL is refused", code != 0 and "https" in out, out)
check("nothing configured by the failures", "newt" not in paths.load_config() and not installed)
print("\n4. install-newt")
print("\n3. install-newt: the API only")
code, out = run(NEWT_ARGS)
check("missing secret without a terminal -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out)
calls.clear()
code, out = run(ARGS, SECRETS)
code, out = run(NEWT_ARGS, {"LLMHOST_NEWT_SECRET": NEWT_SECRET})
c = paths.load_config()
check("succeeds", code == 0, out)
check("newt config saved", c.get("newt") == {"endpoint": "https://pangolin.example.test", "id": "site123"}, c.get("newt"))
check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["issuer"] == ISSUER)
check("allow list saved", c["dashboard_auth"]["allowed_groups"] == ["llm-admins"])
check("dashboard sign-in untouched", "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists())
check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls)
check("dashboard restarted to pick up sign-in", ("restart", "web") in calls, calls)
check("secrets saved 0600", all((f.stat().st_mode & 0o777) == 0o600
for f in (paths.NEWT_SECRET_FILE, paths.OIDC_SECRET_FILE)))
check("secrets read back", paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET
and paths.oidc_secret() == OIDC_SECRET)
cfg_text = paths.CONFIG_FILE.read_text()
check("no secret in config.json", NEWT_SECRET not in cfg_text and OIDC_SECRET not in cfg_text)
check("no secret in the output", NEWT_SECRET not in out and OIDC_SECRET not in out)
check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out)
print("\n5. a re-run keeps what it isn't given")
check("dashboard not restarted", ("restart", "web") not in calls, calls)
check("only the API resource is described", f":{c['api_port']}" in out and f":{c['web_port']}" not in out, out)
check("points to expose-dashboard for the rest", "expose-dashboard" in out and "install-oidc" in out, out)
check("secret saved 0600, not in config or output",
(paths.NEWT_SECRET_FILE.stat().st_mode & 0o777) == 0o600
and NEWT_SECRET not in paths.CONFIG_FILE.read_text() and NEWT_SECRET not in out)
code, out = run(["install-newt", "--newt-id", "site456"])
c = paths.load_config()
check("re-run without secrets succeeds", code == 0, out)
check("changed value updated", c["newt"]["id"] == "site456")
check("other values kept", c["newt"]["endpoint"] == "https://pangolin.example.test"
and c["dashboard_auth"]["allowed_groups"] == ["llm-admins"])
check("secrets kept", paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET and paths.oidc_secret() == OIDC_SECRET)
check("re-run keeps what it isn't given", code == 0 and c["newt"] == {"endpoint": "https://pangolin.example.test", "id": "site456"}
and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out)
print("\n6. newt starts with its credentials in the environment, not its arguments")
print("\n4. newt starts with its credentials in the environment, not its arguments")
seen = {}
import os
real_execve = os.execve
os.execve = lambda exe, argv, env: seen.update(exe=exe, argv=argv, env=env)
newt.run()
os.execve = real_execve
check("runs the installed binary", seen["exe"] == str(newt.binary()))
check("no secret on the command line", seen["argv"] == [str(newt.binary())], seen["argv"])
check("endpoint, id and secret in env",
(seen["env"]["PANGOLIN_ENDPOINT"], seen["env"]["NEWT_ID"], seen["env"]["NEWT_SECRET"])
== ("https://pangolin.example.test", "site456", NEWT_SECRET))
print("\n7. setup/update keep it")
print("\n5. expose-dashboard won't publish behind the API key alone without asking")
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"])
check("refused without a terminal or --force", code != 0 and "install-oidc" in out and "install-otp" in out, out)
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["n"])
check("refused when you say no", code != 0 and "Not published" in out, out)
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test", "--force"])
check("--force walks through it anyway", code == 0 and f":{paths.load_config()['web_port']}" in out
and "dash.example.test" in out, out)
print("\n6. install-oidc")
code, out = run(OIDC_ARGS)
check("missing secret -> error", code != 0 and "LLMHOST_OIDC_SECRET" in out, out)
code, out = run([a for a in OIDC_ARGS if a not in ("--allow-group", "llm-admins")], {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
check("no allow list -> error", code != 0 and "allow" in out, out)
calls.clear()
code, out = run(OIDC_ARGS, {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
c = paths.load_config()
check("succeeds", code == 0, out)
check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["client_id"] == "client-from-provider")
check("newt untouched", c["newt"]["id"] == "site456")
check("dashboard restarted", ("restart", "web") in calls, calls)
check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out)
check("secret 0600, not in config or output", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600
and OIDC_SECRET not in paths.CONFIG_FILE.read_text() and OIDC_SECRET not in out)
code, out = run(["expose-dashboard"])
check("expose-dashboard with OIDC: no question, URL from OIDC", code == 0 and "dash.example.test" in out
and "redirect URI" in out, out)
print("\n7. install-otp")
code, out = run(["install-otp"])
check("needs a terminal", code != 0 and "terminal" in out, out)
FIXED = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
otp.new_secret = lambda: FIXED
code, out = run(["install-otp"], tty_input=["000000", "000001", "000002"])
check("wrong codes -> not paired", code != 0 and not paths.OTP_SECRET_FILE.exists(), out)
calls.clear()
code, out = run(["install-otp"], tty_input=[otp.code_at(FIXED, time.time())])
check("right code -> paired", code == 0 and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
check("secret 0600", (paths.OTP_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
check("showed a QR code and the manual key", "▀" in out and otp.grouped(FIXED) in out, out[:300])
check("says OIDC takes precedence while it's on", "remove-oidc" in out, out)
check("dashboard restarted", ("restart", "web") in calls)
code, out = run(["install-otp"], tty_input=["n"])
check("re-running asks before replacing", code != 0 and "kept" in out and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
code, out = run(["install-otp", "--show"], tty_input=[])
check("--show shows the existing pairing", code == 0 and otp.grouped(FIXED) in out, out[:200])
print("\n8. status and setup keep it all")
code, out = run(["status"])
check("status names the sign-in", "OIDC via " + ISSUER in out, out)
carried = cli.carried_settings(paths.load_config(), set())
check("newt and dashboard_auth carried", "newt" in carried and "dashboard_auth" in carried, carried.keys())
print("\n8. remove-newt")
print("\n9. remove-oidc, then expose-dashboard with codes")
code, out = run(["remove-oidc"])
c = paths.load_config()
check("OIDC off, secret deleted", code == 0 and "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists(), out)
check("says codes work again", "authenticator code" in out, out)
code, out = run(["status"])
check("status: key or code", "API key or authenticator code" in out, out)
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["y", ""])
c = paths.load_config()
check("offers to turn the key off for the dashboard", code == 0 and c.get("dashboard_key_login") is False, out)
code, out = run(["status"])
check("status: codes only", "sign-in authenticator code" in out, out)
check("setup keeps the key switched off", cli.carried_settings(c, set()).get("dashboard_key_login") is False)
print("\n10. remove-otp and remove-newt")
code, out = run(["remove-otp"])
c = paths.load_config()
check("unpaired, key back on", code == 0 and not paths.OTP_SECRET_FILE.exists() and "dashboard_key_login" not in c, out)
calls.clear()
code, out = run(["remove-newt"])
c = paths.load_config()
check("succeeds", code == 0, out)
check("service removed", ("uninstall", "newt") in calls and "newt" not in installed, calls)
check("config back to LAN", "newt" not in c and "dashboard_auth" not in c)
check("secrets deleted", not paths.NEWT_SECRET_FILE.exists() and not paths.OIDC_SECRET_FILE.exists())
check("binary deleted", not newt.binary().exists())
check("dashboard restarted", ("restart", "web") in calls)
check("newt removed", code == 0 and ("uninstall", "newt") in calls and "newt" not in c
and not paths.NEWT_SECRET_FILE.exists() and not newt.binary().exists(), out)
check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models"))
code, out = run(["expose-dashboard"])
check("expose-dashboard needs newt first", code != 0 and "install-newt" in out, out)
code, out = run(["remove-newt"])
check("running it again is harmless", code == 0 and "wasn't installed" in out, out)

View file

@ -0,0 +1,180 @@
"""opencode-install.sh against a fake llm-host API, in a throwaway HOME: new and existing
opencode configs, the default-model choice, the cached-key cleanup, --remove, and the
official installer stood in for by a curl wrapper."""
import json
import os
import subprocess
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
harness.guard(paths, ROOT)
check = harness.Checks()
SCRIPT = harness.REPO / "opencode-install.sh"
KEY = "sk-test-key-for-the-installer"
STATE = {"reasoning": True}
class API(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
if self.headers.get("Authorization") != f"Bearer {KEY}":
self.send_response(401); self.end_headers(); return
if self.path != "/v1/models":
self.send_response(404); self.end_headers(); return
body = json.dumps({"object": "list", "data": [{"id": "some-model", "max_model_len": 131072,
"reasoning": STATE["reasoning"]}]}).encode()
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers()
self.wfile.write(body)
srv = ThreadingHTTPServer(("127.0.0.1", 0), API)
threading.Thread(target=srv.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{srv.server_address[1]}"
PROV = "llmhost-127" # first label of the host, as the CLI and dashboard name it
REAL_CURL = subprocess.run(["bash", "-c", "command -v curl"], capture_output=True, text=True).stdout.strip()
def sandbox(with_opencode=True):
home = Path(tempfile.mkdtemp(dir=ROOT, prefix="home-"))
bin_dir = home / "fakebin"
bin_dir.mkdir()
# Stand-in for the official installer: drop an `opencode` into ~/.opencode/bin.
(bin_dir / "curl").write_text(f"""#!/bin/bash
for a in "$@"; do
if [ "$a" = "https://opencode.ai/install" ]; then
cat <<'EOF'
mkdir -p "$HOME/.opencode/bin"
cp "$FAKE_OPENCODE" "$HOME/.opencode/bin/opencode"
echo "fake opencode installed"
EOF
exit 0
fi
done
exec {REAL_CURL} "$@"
""")
# A fake opencode whose `models` lists the providers' models from opencode.json.
fake_oc = home / "fake-opencode"
fake_oc.write_text(f"""#!/bin/bash
[ "$1" = models ] || exit 0
{sys.executable} -c 'import json,os
c=json.load(open(os.path.expanduser("~/.config/opencode/opencode.json")))
for p,b in (c.get("provider") or {{}}).items():
for m in b.get("models") or {{}}: print(p+"/"+m)'
""")
for f in (bin_dir / "curl", fake_oc):
f.chmod(0o755)
if with_opencode:
(bin_dir / "opencode").symlink_to(fake_oc)
return home, bin_dir, fake_oc
def run(home, bin_dir, fake_oc, *args, key=KEY):
env = {"HOME": str(home), "PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_OPENCODE": str(fake_oc)}
if key is not None:
env["LLMHOST_API_KEY"] = key
r = subprocess.run(["bash", str(SCRIPT), "--", *args], env=env, capture_output=True, text=True,
stdin=subprocess.DEVNULL, start_new_session=True, timeout=60) # no terminal
return r.returncode, r.stdout + r.stderr
def conf(home):
return json.loads((home / ".config/opencode/opencode.json").read_text())
print("\n1. a new opencode user")
home, b, oc = sandbox(with_opencode=False)
code, out = run(home, b, oc, "--url", URL)
check("succeeds", code == 0, out)
check("installs opencode through the official installer", "fake opencode installed" in out
and (home / ".opencode/bin/opencode").exists(), out)
c = conf(home)
p = c["provider"][PROV]
check("provider added", p["options"]["baseURL"] == URL + "/v1", p)
check("key referenced by file, not inlined", p["options"]["apiKey"] == "{file:" + str(home / f".config/opencode/{PROV}.key") + "}"
and KEY not in json.dumps(c), p["options"])
check("made the default model", c.get("model") == f"{PROV}/default", c.get("model"))
check("schema set", c.get("$schema") == "https://opencode.ai/config.json")
check("context from the server", p["models"]["default"]["limit"] == {"context": 131072, "output": 65536})
check("thinking model: effort menu off", p["models"]["default"].get("variants", {}).get("high") == {"disabled": True})
kf = home / f".config/opencode/{PROV}.key"
check("key file saved 0600", kf.read_text().strip() == KEY and (kf.stat().st_mode & 0o777) == 0o600)
check("key not echoed", KEY not in out)
check("opencode sees it", f"opencode sees {PROV}/default" in out, out)
check("no backup for a config that didn't exist", not (home / ".config/opencode/opencode.json.before-llmhost").exists())
print("\n2. an existing opencode user")
home, b, oc = sandbox()
cd = home / ".config/opencode"; cd.mkdir(parents=True)
mine = {"$schema": "https://opencode.ai/config.json", "theme": "dark", "model": "anthropic/some-model",
"provider": {"other": {"npm": "x", "models": {"m": {}}}}}
(cd / "opencode.json").write_text(json.dumps(mine))
auth = home / ".local/share/opencode/auth.json"; auth.parent.mkdir(parents=True)
auth.write_text(json.dumps({PROV: {"type": "api", "key": "stale"}, "anthropic": {"type": "oauth"}}))
STATE["reasoning"] = False
code, out = run(home, b, oc, "--url", URL + "/v1/")
c = conf(home)
check("succeeds", code == 0, out)
check("didn't reinstall opencode", "already installed" in out and not (home / ".opencode").exists(), out)
check("other settings kept", c["theme"] == "dark" and "other" in c["provider"])
check("their default model kept (no terminal to ask on)", c["model"] == "anthropic/some-model", c["model"])
check("says how to pick it", "/models" in out, out)
check("original backed up", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
check("trailing /v1/ normalised", c["provider"][PROV]["options"]["baseURL"] == URL + "/v1")
check("non-thinking model: no variants", "variants" not in c["provider"][PROV]["models"]["default"])
a = json.loads(auth.read_text())
check("stale cached key dropped, others kept", PROV not in a and "anthropic" in a, a)
code, out = run(home, b, oc, "--url", URL, "--default")
check("--default switches the model", conf(home)["model"] == f"{PROV}/default")
check("backup not overwritten on a re-run", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
code, out = run(home, b, oc, "--url", URL)
check("a re-run keeps it the default", conf(home)["model"] == f"{PROV}/default")
STATE["reasoning"] = True
print("\n3. --remove")
code, out = run(home, b, oc, "--url", URL, "--remove", key=None)
c = conf(home)
check("succeeds without a key", code == 0, out)
check("provider gone, others kept", PROV not in c["provider"] and "other" in c["provider"], c)
check("model that pointed at it dropped", "model" not in c, c)
check("key file gone", not (cd / f"{PROV}.key").exists())
print("\n4. refusals")
home, b, oc = sandbox()
code, out = run(home, b, oc, "--url", URL, key="sk-wrong")
check("wrong key -> error", code != 0 and "rejected" in out, out)
check("nothing written after a wrong key", not (home / ".config/opencode").exists())
code, out = run(home, b, oc, "--url", URL, key=None)
check("no key and no terminal -> error", code != 0 and "no API key" in out, out)
code, out = run(home, b, oc, "--url", "ftp://x")
check("bad URL -> error", code != 0 and "https://" in out, out)
code, out = run(home, b, oc, "--url", "http://127.0.0.1:9")
check("unreachable -> error", code != 0 and "couldn't reach" in out, out)
cd = home / ".config/opencode"; cd.mkdir(parents=True)
(cd / "opencode.json").write_text("{ not json")
code, out = run(home, b, oc, "--url", URL)
check("broken JSON left alone", code != 0 and (cd / "opencode.json").read_text() == "{ not json", out)
(cd / "opencode.json").unlink()
(cd / "opencode.jsonc").write_text('{ // mine\n "theme": "dark" }')
code, out = run(home, b, oc, "--url", URL)
check("a .jsonc is never rewritten; the block is printed", code == 0 and "by hand" in out
and (cd / "opencode.jsonc").read_text().startswith("{ // mine") and not (cd / "opencode.json").exists(), out)
print("\n5. --help works when run as `bash -c`")
r = subprocess.run(["bash", "-c", SCRIPT.read_text(), "--", "--help"], capture_output=True, text=True)
check("prints usage", r.returncode == 0 and "--url" in r.stdout, r.stdout + r.stderr)
srv.shutdown()
check.done(ROOT)

145
tests/test_otp.py Normal file
View file

@ -0,0 +1,145 @@
"""Authenticator codes: TOTP against RFC 6238, the verifier's replay and lockout rules, the
QR encoder against reference matrices, and code sign-in on the dashboard."""
import http.client
import json
import sys
import threading
from http.server import ThreadingHTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import otp, paths, qr
from llmhost.web import server as web
harness.guard(paths, ROOT)
check = harness.Checks()
print("\n1. TOTP matches RFC 6238 (SHA-1 vectors)")
RFC = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" # base32 of "12345678901234567890"
for t, want in ((59, "94287082"), (1111111109, "07081804"), (1111111111, "14050471"),
(1234567890, "89005924"), (2000000000, "69279037"), (20000000000, "65353130")):
check(f"t={t}", otp.code_at(RFC, t, digits=8) == want, otp.code_at(RFC, t, digits=8))
check("6 digits is the last six", otp.code_at(RFC, 59) == "287082")
check("new secrets are 160 bits of base32", len(otp.new_secret()) == 32 and otp.new_secret() != otp.new_secret())
uri = otp.pairing_uri("ABCDEFGH", "mybox.local")
check("pairing link", uri.startswith("otpauth://totp/llm-host:mybox.local?") and "secret=ABCDEFGH" in uri
and "issuer=llm-host" in uri and "period=30" in uri, uri)
check("grouped for typing", otp.grouped("ABCDEFGHIJ") == "ABCD EFGH IJ")
print("\n2. the verifier")
S = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
now = [1_700_000_000.0]
v = otp.Verifier(S, clock=lambda: now[0])
code = otp.code_at(S, now[0])
check("current code accepted", v.check(code) == "ok")
check("same code again refused (replay)", v.check(code) == "wrong")
now[0] += 30
check("previous step's code refused once a later one was used", v.check(otp.code_at(S, now[0] - 30)) == "wrong")
check("drift: next step's code accepted", v.check(otp.code_at(S, now[0] + 30)) == "ok")
check("spaces and dashes tolerated", otp.matching_step(S, " ".join(otp.code_at(S, now[0])), now[0]) is not None)
check("wrong length refused", otp.matching_step(S, "12345", now[0]) is None)
v2 = otp.Verifier(S, clock=lambda: now[0])
for _ in range(otp.MAX_FAILURES):
v2.check("000000")
check(f"locked after {otp.MAX_FAILURES} wrong codes", v2.check(otp.code_at(S, now[0])) == "locked" and v2.locked_for() > 0)
now[0] += otp.FAIL_WINDOW + 1
check("unlocked after the window", v2.check(otp.code_at(S, now[0])) == "ok")
print("\n3. QR codes match reference matrices")
golden = json.loads((harness.FIXTURES / "qr_golden.json").read_text())
for text, g in golden.items():
q = qr.QR(text, mask=g["mask"])
rows = ["".join("1" if c else "0" for c in r) for r in q.m]
check(f"v{g['version']} ({len(text)} bytes)", q.version == g["version"] and rows == g["rows"])
q = qr.QR(otp.pairing_uri(otp.new_secret(), "a-rather-long-hostname.example.local"))
check("a pairing link fits", 1 <= q.version <= qr.MAX_VERSION and 0 <= q.mask <= 7)
check("terminal rendering: two modules per row, with a quiet zone", len(q.terminal()) == (q.size + 4 + 1) // 2)
try:
qr.QR("x" * 300)
check("too long is refused", False)
except ValueError:
check("too long is refused", True)
print("\n4. code sign-in on the dashboard")
KEY = "sk-test"
class StubSampler:
def snapshot(self):
return {"ok": True}
def reset_stats(self):
pass
def serve(**kw):
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, **kw))
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
def req(srv, method, path, headers=None, body=None):
c = http.client.HTTPConnection("127.0.0.1", srv.server_address[1], timeout=5)
c.request(method, path, body=body, headers=headers or {})
r = c.getresponse()
data = r.read()
cookies = [v for k, v in r.getheaders() if k.lower() == "set-cookie"]
c.close()
return r.status, data, cookies
HOST = {"Host": "mybox.local:11340"}
SAME = {**HOST, "Origin": "http://mybox.local:11340", "Content-Type": "application/json"}
clock = [1_800_000_000.0]
verifier = otp.Verifier(S, clock=lambda: clock[0])
srv = serve(otp=verifier)
cfg = json.loads(req(srv, "GET", "/auth/config", HOST)[1])
check("config: key and codes", cfg == {"mode": "key", "key": True, "otp": True, "user": None, "name": None}, cfg)
check("key still works", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 200)
body = json.dumps({"code": otp.code_at(S, clock[0])})
check("code from another origin refused", req(srv, "POST", "/auth/otp", {**SAME, "Origin": "https://evil.test"}, body)[0] == 403)
check("code without an Origin refused", req(srv, "POST", "/auth/otp", HOST, body)[0] == 403)
st, data, cookies = req(srv, "POST", "/auth/otp", SAME, body)
sess = cookies[0].split(";")[0] if cookies else ""
check("right code -> session", st == 200 and sess.startswith("llmhost_session="), (st, data))
check("session cookie HttpOnly, Lax; not Secure over plain http",
"HttpOnly" in cookies[0] and "SameSite=Lax" in cookies[0] and "Secure" not in cookies[0], cookies)
check("session opens the API", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 200)
check("session POST from this page works", req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess})[0] == 200)
check("session POST from another origin refused",
req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
cfg = json.loads(req(srv, "GET", "/auth/config", {**HOST, "Cookie": sess})[1])
check("config names the session", cfg["user"] == "authenticator", cfg)
check("same code can't be reused", req(srv, "POST", "/auth/otp", SAME, body)[0] == 401)
clock[0] += 60
st, _, cookies = req(srv, "POST", "/auth/otp", {**SAME, "X-Forwarded-Proto": "https"},
json.dumps({"code": otp.code_at(S, clock[0])}))
check("behind HTTPS the cookie is Secure", st == 200 and "Secure" in cookies[0], cookies)
for _ in range(otp.MAX_FAILURES):
req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "000000"}))
st, data, _ = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
check("too many wrong codes -> 429", st == 429 and json.loads(data)["retry_after"] > 0, (st, data))
st, _, cookies = req(srv, "POST", "/auth/logout", {**SAME, "Cookie": sess})
check("sign out clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
check("old session no longer works", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 401)
srv.shutdown()
print("\n5. key sign-in switched off for the dashboard")
v3 = otp.Verifier(S, clock=lambda: clock[0])
srv = serve(otp=v3, key_login=False)
check("config says so", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["key"] is False)
check("the key no longer opens the dashboard", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
st, _, cookies = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
check("a code still does", st == 200 and req(srv, "GET", "/api/status", {**HOST, "Cookie": cookies[0].split(";")[0]})[0] == 200)
srv.shutdown()
print("\n6. no codes without install-otp")
srv = serve()
check("config: no otp", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["otp"] is False)
check("/auth/otp is 404", req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "123456"}))[0] == 404)
srv.shutdown()
check.done(ROOT)

View file

@ -140,6 +140,8 @@ req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
with urllib.request.urlopen(req, timeout=10) as r:
d = json.loads(r.read())
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
check("reports context and whether it thinks", d["data"][0]["max_model_len"] == 262144
and d["data"][0]["reasoning"] is False, d)
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
VOUTER = 18233