From e48517b1cfa337e75323fff8ac7cc73a4c516b27 Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 15:01:12 -0800 Subject: [PATCH 01/10] Setup: keep the dashboard's reasoning setting across an update cmd_setup rebuilds config.json from the plan, and the reasoning setting isn't part of the plan -- the dashboard writes it into the same file. So every `llmhost update` (setup --yes under the hood) silently put every model back to "Model default", losing a setting the user had chosen in the UI. Carry it over, minus models that no longer fit. The helper exists so the reason is on the record rather than implied by a dict literal; its tests cover the empty and no-longer-fits cases that must not write the key at all. Co-Authored-By: Claude Opus 5 (1M context) --- llmhost/cli.py | 10 ++++++++++ tests/test_reasoning.py | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/llmhost/cli.py b/llmhost/cli.py index afbcdda..99f7036 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -111,6 +111,15 @@ def cmd_plan(a): say("\nNothing fits. " + (p.get("reason") or "")) +def carried_settings(old, names): + """Settings setup must not reset. The plan is setup's to rebuild, but the reasoning + setting belongs to the dashboard, which writes it into the same file -- without this an + `llmhost update` would quietly put every model back to "Model default". Models that no + longer fit lose their setting along with their plan.""" + kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names} + return {"reasoning": kept} if kept else {} + + def cmd_setup(a): info = hw.detect() cat = paths.load_catalog() @@ -169,6 +178,7 @@ def cmd_setup(a): "models": p["models"], "excluded": p["excluded"], "active": active, p["backend"]: {**old.get(p["backend"], {}), **backend_info}, } + cfg.update(carried_settings(old, names)) paths.save_config(cfg) key = paths.api_key(create=True) diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py index 6e17ddd..4ed7cba 100644 --- a/tests/test_reasoning.py +++ b/tests/test_reasoning.py @@ -88,4 +88,23 @@ check("no server default -> client kwargs preserved", check("a non-dict from the client isn't merged into", inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"}) +print("\n5. the setting survives a setup re-run (`llmhost update`)") +from llmhost import cli +NAMES = ["qwen3.8-27b", "ornith-1.5-9b"] +check("a set choice is carried over", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh"}}) +check("every model's choice is kept, not just the active one", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh", "ornith-1.5-9b": "off"}}) +check("a model that no longer fits is dropped", + cli.carried_settings({"reasoning": {"qwen3.8-27b": "xhigh", "gone-70b": "low"}}, NAMES) + == {"reasoning": {"qwen3.8-27b": "xhigh"}}) +check("nothing set -> no key written", cli.carried_settings({}, NAMES) == {}) +check("empty setting -> no key written", cli.carried_settings({"reasoning": {}}, NAMES) == {}) +check("no model still fits -> no key written", + cli.carried_settings({"reasoning": {"gone-70b": "low"}}, NAMES) == {}) +check("setup's own keys are not touched", + set(cli.carried_settings({"reasoning": {"qwen3.8-27b": "low"}}, NAMES)) == {"reasoning"}) + check.done(ROOT) From e24c0b771297b024481cbea97c5dbcae2fbe8f5d Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Tue, 3 Nov 2026 15:01:26 -0800 Subject: [PATCH 02/10] Reasoning effort is the dashboard's to set, not the client's One model is loaded at a time under one setting, and that setting belongs next to the model it applies to -- the same reason the client can't switch models. So the proxy now takes a client's reasoning settings off the request before applying the dashboard's: a top-level reasoning_effort, and enable_thinking or reasoning_effort inside chat_template_kwargs. Other template kwargs, which llm-host has no opinion about, still pass through. This reverses the precedence the proxy had (a client's own kwargs won, mirroring mlx_lm's own rule), which was the wrong model for a single-model server: clients offer a generic menu -- opencode's low/medium/high -- and a level the template doesn't define makes it raise, so every request failed with nothing on the user's screen to explain it. - opencode: the provider block disables all three of opencode's effort levels instead of curating them. A chooser there would be a menu that does nothing. - Deletes the nearest-effort mapping (EFFORT_SCALE, nearest_effort, plan.effort_levels, the effort_levels= parameter through both backends): it existed only to rescue a client-supplied level, and none survives now. - plan.REASONING_KEYS names the knobs this server drives, with a test asserting it stays exactly equal to what reasoning_kwargs can emit -- so a new template knob can't be added without also taking it away from clients. - Two strings that still described a menu of models, from before the block held a single entry. Verified against the live MLX server: with the dashboard on xhigh, five request shapes (nothing, enable_thinking: false, effort low top-level, effort low in kwargs, and the off-scale "turbo" that used to 404) all answer identically, and the reply tracks the dashboard alone as it moves off / low / xhigh. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 33 ++++++++++++-------- llmhost/backends/mlx.py | 5 ++-- llmhost/backends/proxy.py | 54 +++++++++++++++------------------ llmhost/backends/vllm.py | 5 ++-- llmhost/cli.py | 2 +- llmhost/opencode.py | 38 ++++++++--------------- llmhost/plan.py | 27 ++++------------- tests/test_opencode.py | 22 ++++++++------ tests/test_proxy.py | 63 ++++++++++++++++++++++++++------------- tests/test_reasoning.py | 36 ++++++++-------------- 10 files changed, 134 insertions(+), 151 deletions(-) diff --git a/README.md b/README.md index 71ffa6c..45b88ba 100644 --- a/README.md +++ b/README.md @@ -95,13 +95,13 @@ alias, and `/v1/models` reports the real slug. The local entry is labelled with `llmhost switch`, the dashboard and `llmhost update` keep that label current. A config that still points at a specific model (`llmhost/qwen3.8-27b`) is migrated to `llmhost/default` the next time llm-host writes the block. -opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, and a level the model's -template doesn't define makes every request fail. So the block carries `variants` that hide the levels the -loaded model lacks and add the ones it has (Qwen3.8 27B: no `high`, plus `xhigh`). A pasted remote block can't -follow a later switch, so the proxy also maps a level the model lacks to the nearest one it has (`high` → -`xhigh`); a stale menu entry still works. +opencode offers its own `low`/`medium`/`high` effort menu for any reasoning model, so the block carries +`variants` that switch all three off. The effort level is set on the dashboard, next to the model it applies +to, and the proxy drops whatever a client sends — a chooser in the client would be a menu that silently does +nothing, listing levels the loaded model's template may not even define. -To serve a different model, switch the server: `llmhost switch ` or the dashboard. Clients don't choose. +Neither the model nor its reasoning setting is the client's to choose: both change on the dashboard (or with +`llmhost switch `), because one model is loaded at a time and one setting applies to it. Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is @@ -140,12 +140,16 @@ Ornith 1.5 9B takes only `enable_thinking`. So the dashboard builds the chooser model's own template, with the level names from `catalog.json` (`"effort": {"levels": [...]}`) — a level the template doesn't know is never offered or sent. -The setting is a default for requests that don't ask for anything: the proxy adds it to chat -completions, and a `chat_template_kwargs` key the client sets itself always wins. Changing it -takes effect on the next request with no reload, so the model stays in memory. +The dashboard is the only place it is set. The proxy puts the setting on every chat completion +and takes the client's own out first — both a top-level `reasoning_effort` and `enable_thinking` +or `reasoning_effort` inside `chat_template_kwargs`. Template kwargs llm-host has no opinion +about are passed through untouched. Changing the setting takes effect on the next request with no +reload, so the model stays in memory. -This works the same on vLLM and MLX. A client's own top-level `reasoning_effort` also wins over -the dashboard's level, and one the model lacks is mapped to the nearest level it has. +Clients are ignored here rather than obeyed because one model is loaded at a time under one +setting, and because a client's menu is generic: opencode offers `high`, which Qwen3.8's template +raises on, and the user would see every request fail with nothing on their screen to explain it. +This works the same on vLLM and MLX. ## How models are chosen @@ -193,9 +197,9 @@ python3 tests/test_opencode.py # or run one directly | | | |---|---| | `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache | -| `tests/test_proxy.py` | model names, effort mapping, upstream key, streamed-run counting, against a fake server | +| `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_reasoning.py` | effort options matching the real chat templates | +| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update | ## Continuing on an NVIDIA box @@ -249,5 +253,8 @@ On macOS the services are launchd agents, so they run while you're logged in. - One model loaded at a time. Asking the API for a different one returns `404 model_not_found` naming the loaded model, rather than answering with it. +- Reasoning effort is set on the dashboard, not by the client. A request's own + `reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's + 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 expose them to the internet. diff --git a/llmhost/backends/mlx.py b/llmhost/backends/mlx.py index 616a6f6..59dbea8 100644 --- a/llmhost/backends/mlx.py +++ b/llmhost/backends/mlx.py @@ -15,7 +15,7 @@ import sys import threading import time -from .. import hfcache, paths, plan +from .. import hfcache, paths from . import proxy VENV = paths.DATA / "venv-mlx" @@ -104,8 +104,7 @@ 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), - effort_levels=plan.effort_levels(entry, controls))) + aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls))) proxy.kill_stale(inner, VENV, "mlx_lm") exe = str(VENV / "bin/mlx_lm.server") diff --git a/llmhost/backends/proxy.py b/llmhost/backends/proxy.py index 5edf1bf..8440d32 100644 --- a/llmhost/backends/proxy.py +++ b/llmhost/backends/proxy.py @@ -6,8 +6,8 @@ and, so that clients see the same API on either backend: - rejects a request for a model that isn't the loaded one (404 model_not_found), and rewrites the request's "model" to the name the server knows it by; /v1/models answers with the served name, - - applies the dashboard's reasoning setting to chat requests, and maps an effort level - the model doesn't have (a client's generic "high", say) to the nearest one it does, + - applies the dashboard's reasoning setting to chat requests, dropping any the client + sent: the model and its reasoning setting are both the dashboard's to choose, - counts in-flight requests and tokens and records each finished request for the dashboard (/llmhost/metrics, localhost only). """ @@ -73,11 +73,10 @@ def _uncached(usage): def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None, - upstream_model="default_model", upstream_key=None, effort_levels=()): + upstream_model="default_model", upstream_key=None): """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). effort_levels: the levels this - model's template accepts; an unknown one from a client is mapped to the nearest.""" + on to an inner server that checks keys itself (vLLM).""" # 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)} @@ -143,16 +142,23 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso "type": "invalid_request_error", "code": "model_not_found", "param": "model"}}) return False - def _fit_effort(self, holder, k): - """Map holder[k], a client's effort level, onto one this model accepts. Clients - offer a generic menu (opencode: low/medium/high), and a level the template - doesn't define makes it raise -- every request then fails until the user finds - the setting. The nearest level is what they meant.""" - v = holder.get(k) - if effort_levels and isinstance(v, str) and v not in effort_levels: - fit = plan.nearest_effort(v, effort_levels) - if fit: - holder[k] = fit + def _set_reasoning(self, body): + """Put the dashboard's reasoning setting on the request, and drop whatever the + client asked for. The setting belongs to the dashboard for the same reason the + model does: one model is loaded at a time, under one setting, and a client's + generic menu (opencode offers low/medium/high) lists levels this template may + not even define -- one of those would make it raise, failing every request from + a client whose user can't see why. The client's other template kwargs, which + llm-host has no opinion about, are left alone.""" + body.pop("reasoning_effort", None) # the OpenAI-style top-level field + theirs = body.get("chat_template_kwargs") + kw = {k: v for k, v in theirs.items() if k not in plan.REASONING_KEYS} \ + if isinstance(theirs, dict) else {} + kw.update(reasoning() if reasoning else {}) + if kw: + body["chat_template_kwargs"] = kw + else: + body.pop("chat_template_kwargs", None) def do_POST(self): if not self._authed(): @@ -169,22 +175,10 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso if isinstance(body, dict): if self.path.startswith("/v1/") and not self._model_ok(body): return + # Only chat completions go through a chat template, so only they can + # carry a reasoning setting. if "chat/completions" in self.path: - theirs = body.get("chat_template_kwargs") - # Server-side reasoning default. Only chat completions go through a - # chat template, and a setting the client made itself always wins -- - # the same precedence mlx_lm applies to its own --chat-template-kwargs. - kw = reasoning() if reasoning else {} - if kw: - mine = dict(kw) - if "reasoning_effort" in body: # the OpenAI-style top-level field - mine.pop("reasoning_effort", None) - if isinstance(theirs, dict): - mine.update(theirs) - body["chat_template_kwargs"] = theirs = mine - self._fit_effort(body, "reasoning_effort") - if isinstance(theirs, dict): - self._fit_effort(theirs, "reasoning_effort") + self._set_reasoning(body) # Name the loaded model the way the inner server knows it (mlx_lm would # otherwise try to load a model matching the name it's given). body["model"] = upstream_model diff --git a/llmhost/backends/vllm.py b/llmhost/backends/vllm.py index 70a01bc..bbcb3e8 100644 --- a/llmhost/backends/vllm.py +++ b/llmhost/backends/vllm.py @@ -164,7 +164,7 @@ def run_server(cfg, entry, choice, args): """Start the proxy on api_port, then `vllm serve` as a child on api_port+1 (args). vLLM keeps its own API key, so the inner port isn't open to anyone else on the box; the proxy checks the client's key and sends ours on.""" - from .. import hfcache, plan + from .. import hfcache from . import proxy port = cfg["api_port"] inner = port + 1 @@ -175,8 +175,7 @@ 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, - effort_levels=plan.effort_levels(entry, controls))) + upstream_model=entry["name"], upstream_key=key)) 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. diff --git a/llmhost/cli.py b/llmhost/cli.py index 99f7036..5ac5f00 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -361,7 +361,7 @@ def cmd_switch(a): paths.save_config(cfg) service.restart("model") if opencode.sync(cfg): - say(f"Updated opencode's model list; {a.model} is the one marked loaded.") + say(f"opencode's LLMHost (Local) provider now names {a.model} as the default model.") say(f"Switched to {a.model}. Watch it load with: llmhost watch") diff --git a/llmhost/opencode.py b/llmhost/opencode.py index e0adf31..090bb7a 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -22,7 +22,7 @@ import subprocess from pathlib import Path from urllib.parse import urlsplit -from . import hfcache, paths, plan +from . import paths, plan PROVIDER = "llmhost" DISPLAY = "LLMHost" @@ -127,28 +127,16 @@ def model_label(active, label, name_it): # A model's template defines its own set, and one it lacks makes the template raise, so # the block hides those and adds the model's own. (The proxy also maps a stray level to # the nearest real one, so a pasted block that predates a switch still works.) +# The reasoning levels opencode offers of its own accord for a model marked `reasoning`. OPENCODE_EFFORTS = ("low", "medium", "high") -def _effort_levels(choice): - """The active model's effort levels: from its chat template once downloaded (what the - proxy itself goes by), from the catalog before that.""" - try: - entry = plan.catalog_entry(paths.load_catalog(), choice["name"]) - except (KeyError, OSError, ValueError): - return () - if not entry.get("reasoning"): - return () - if choice.get("repo") and hfcache.repo_dir(choice["repo"]).exists(): - return plan.effort_levels(entry, hfcache.template_controls(choice["repo"])) - return tuple((entry.get("effort") or {}).get("levels") or ()) - - -def effort_variants(levels): - """opencode `variants` for a model accepting `levels`.""" - v = {l: {"disabled": True} for l in OPENCODE_EFFORTS if l not in levels} - v.update({l: {"reasoningEffort": l} for l in levels if l not in OPENCODE_EFFORTS}) - return v +def effort_variants(): + """opencode `variants` that switch its reasoning menu off. The effort level is set on + llm-host's dashboard and the proxy drops whatever a client asks for, so a chooser here + would be a menu that silently does nothing -- and whose levels this model's template + may not even define. One model, one setting, one place to change it.""" + return {level: {"disabled": True} for level in OPENCODE_EFFORTS} def provider_block(cfg, host, key_path, label, mark_loaded=False): @@ -161,10 +149,10 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False): entry = {"name": model_label(active, label, mark_loaded), "tool_call": True, "limit": {"context": ctx, "output": min(65536, ctx // 2)}} if (active or {}).get("reasoning"): + # `reasoning` so opencode renders the thinking blocks; `variants` so it doesn't + # offer to set the effort itself. entry["reasoning"] = True - variants = effort_variants(_effort_levels(active)) - if variants: - entry["variants"] = variants + entry["variants"] = effort_variants() models = {plan.SERVED_ALIAS: entry} return { "npm": "@ai-sdk/openai-compatible", @@ -393,8 +381,8 @@ def remove(prov_ids=None, local=True, host=None, every=False): def sync(cfg): - """Refresh an existing local provider block -- after a model switch, so the "loaded" - marker and the model list keep up. Never adds one: if opencode isn't wired up here, + """Refresh an existing local provider block -- after a model switch, so the entry's + name and limits keep up with what's loaded. Never adds one: if opencode isn't wired up here, switching a model is no reason to wire it. Returns the provider id, or None.""" path = config_file() if not path.exists(): diff --git a/llmhost/plan.py b/llmhost/plan.py index a419633..e5e08e3 100644 --- a/llmhost/plan.py +++ b/llmhost/plan.py @@ -200,6 +200,11 @@ def reasoning_options(entry, choice, controls): return opts if len(opts) > 1 else [] +# The chat-template knobs this server drives. A client's own values for these are dropped +# on the way through the proxy: the setting is the dashboard's, not the client's. +REASONING_KEYS = ("enable_thinking", "reasoning_effort") + + def reasoning_kwargs(value, entry, controls): """chat_template_kwargs for a setting, or {} for "default"/anything unsupported.""" if not value or value == DEFAULT or not entry.get("reasoning"): @@ -211,25 +216,3 @@ def reasoning_kwargs(value, entry, controls): return {"reasoning_effort": value} return {} - -# Effort levels in order, for mapping a level a model lacks onto the nearest it has. -EFFORT_SCALE = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] - - -def effort_levels(entry, controls): - """The effort levels this model's template accepts, or () if it takes none.""" - levels = (entry.get("effort") or {}).get("levels") or [] - return tuple(levels) if entry.get("reasoning") and controls.get("effort") else () - - -def nearest_effort(value, levels): - """The level in `levels` closest to `value` on EFFORT_SCALE; on a tie, the higher one - (asking for "high" between medium and xhigh means wanting more, not less). None when - either is off the scale.""" - if value not in EFFORT_SCALE: - return None - want = EFFORT_SCALE.index(value) - known = [l for l in levels if l in EFFORT_SCALE] - if not known: - return None - return min(known, key=lambda l: (abs(EFFORT_SCALE.index(l) - want), -EFFORT_SCALE.index(l))) diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 2a9510b..0f73e2d 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -309,18 +309,22 @@ check("model is /", snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"], (snip["model"], list(block["models"]))) -check.section("24. the block offers only the effort levels the loaded model accepts") -check("qwen3.8: hide high, add xhigh", - opencode.effort_variants(("low", "medium", "xhigh")) == {"high": {"disabled": True}, - "xhigh": {"reasoningEffort": "xhigh"}}, - opencode.effort_variants(("low", "medium", "xhigh"))) -check("no levels: hide opencode's whole menu", - opencode.effort_variants(()) == {l: {"disabled": True} for l in ("low", "medium", "high")}) +check.section("24. the block never offers a reasoning chooser of its own") +check("opencode's whole menu is switched off", + opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")}, + opencode.effort_variants()) q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") ent = q["models"]["default"] -check("qwen3.8 block (not downloaded: catalog levels)", - ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent) +check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent) +check("but every effort level is disabled", + ent.get("variants") == {l: {"disabled": True} for l in ("low", "medium", "high")}, ent) +check("no variant carries a reasoningEffort to send", + not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"]) +check("the model levels from the catalog are not offered either", + not ({"xhigh"} & set(ent["variants"])), ent["variants"]) nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local") check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"]) +check("one entry only, named for the alias, so the client can't pick a model either", + list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"])) check.done(ROOT) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 96044e0..5cbd7a7 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -147,7 +147,6 @@ vstats = proxy.Stats() vstats.ready = True serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",), upstream_model="qwen3.8-27b", upstream_key="sk-inner", - effort_levels=("low", "medium", "xhigh"), reasoning=lambda: {"reasoning_effort": "low"}), VOUTER) seen.clear(); auths.clear() check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200) @@ -155,31 +154,53 @@ check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27 check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1]) check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404) -check.section("10. effort levels the model lacks are mapped to the nearest it has") -for asked, sent in (("high", "xhigh"), ("medium", "medium"), ("xhigh", "xhigh"), - ("minimal", "low"), ("max", "xhigh")): - seen.clear() - post(None, port=VOUTER, reasoning_effort=asked) - check(f"top-level {asked} -> {sent}", seen[-1].get("reasoning_effort") == sent, seen[-1]) -seen.clear() -post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "high"}) -check("inside chat_template_kwargs too", seen[-1]["chat_template_kwargs"].get("reasoning_effort") == "xhigh", - seen[-1].get("chat_template_kwargs")) -seen.clear() -post(None, port=VOUTER, reasoning_effort="bogus") -check("an unknown word is left for the server to reject", seen[-1].get("reasoning_effort") == "bogus", seen[-1]) +check.section("10. the reasoning setting is the dashboard's; a client can't set it") seen.clear() post(None, port=VOUTER) -check("dashboard setting applied when the client sets none", +check("dashboard setting applied when the client asks for nothing", seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) seen.clear() post(None, port=VOUTER, reasoning_effort="xhigh") -check("a client's own top-level level wins over the dashboard's", - "reasoning_effort" not in (seen[-1].get("chat_template_kwargs") or {}) - and seen[-1].get("reasoning_effort") == "xhigh", seen[-1]) -check("mapping only where a model has levels", - [plan.nearest_effort("high", ()), plan.nearest_effort("high", ("low", "high"))] == [None, "high"]) -check("a tie goes to the higher level", plan.nearest_effort("high", ("medium", "xhigh")) == "xhigh") +check("a client's top-level reasoning_effort never reaches the model", + "reasoning_effort" not in seen[-1], seen[-1]) +check("...and the dashboard's setting is what goes instead", + seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "xhigh"}) +check("nor one inside chat_template_kwargs", + seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False}) +check("a client can't turn thinking off either", + "enable_thinking" not in seen[-1]["chat_template_kwargs"], seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs={"enable_thinking": False, "custom_var": 7}) +check("template kwargs llm-host has no opinion about are left alone", + seen[-1]["chat_template_kwargs"] == {"custom_var": 7, "reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, chat_template_kwargs="not a dict") +check("junk in chat_template_kwargs is replaced, not merged into", + seen[-1]["chat_template_kwargs"] == {"reasoning_effort": "low"}, seen[-1]) +seen.clear() +post(None, port=VOUTER, path="/v1/completions", reasoning_effort="xhigh") +check("a non-chat request is left as it came (no template, no setting)", + seen[-1].get("reasoning_effort") == "xhigh" and "chat_template_kwargs" not in seen[-1], seen[-1]) + +check.section("10b. with nothing set on the dashboard, the client's setting is still dropped") +NOUTER = 18234 +nstats = proxy.Stats() +nstats.ready = True +serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, nstats, + upstream_model="qwen3.8-27b", reasoning=lambda: {}), NOUTER) +seen.clear() +post(None, port=NOUTER, reasoning_effort="xhigh", chat_template_kwargs={"enable_thinking": False}) +check("both forms dropped", "reasoning_effort" not in seen[-1], seen[-1]) +check("and no empty kwargs left behind for the template to read", + "chat_template_kwargs" not in seen[-1], seen[-1]) +seen.clear() +post(None, port=NOUTER, chat_template_kwargs={"custom_var": 7}) +check("an unrelated kwarg still survives on its own", + seen[-1]["chat_template_kwargs"] == {"custom_var": 7}, seen[-1]) check.section("11. a streamed run is counted from its usage chunk, and recorded") before = vstats.snapshot() diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py index 4ed7cba..f0cc508 100644 --- a/tests/test_reasoning.py +++ b/tests/test_reasoning.py @@ -63,30 +63,18 @@ else: check("no other catalog model claims levels", [m for m in cat.values() if m.get("effort") and m["name"] != "qwen3.8-27b"] == []) -print("\n4. a client's own kwargs win over the server default") -def inject(server_kw, client_body): - """The precedence rule from the proxy, which mirrors mlx_lm's own.""" - if not server_kw: - return client_body.get("chat_template_kwargs") - mine = dict(server_kw) - theirs = client_body.get("chat_template_kwargs") - if isinstance(theirs, dict): - mine.update(theirs) - return mine - -check("server default applied when client says nothing", - inject({"reasoning_effort": "low"}, {}) == {"reasoning_effort": "low"}) -check("client overrides the same key", - inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"reasoning_effort": "xhigh"}}) - == {"reasoning_effort": "xhigh"}) -check("client's other keys survive alongside", - inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"enable_thinking": False}}) - == {"reasoning_effort": "low", "enable_thinking": False}) -check("no server default -> body untouched", inject({}, {}) is None) -check("no server default -> client kwargs preserved", - inject({}, {"chat_template_kwargs": {"enable_thinking": False}}) == {"enable_thinking": False}) -check("a non-dict from the client isn't merged into", - inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"}) +print("\n4. every knob the dashboard can set is one the proxy takes away from clients") +# The proxy drops plan.REASONING_KEYS from a client's request before applying the +# dashboard's setting. If reasoning_kwargs learns a new template knob and this list +# doesn't, a client could set that knob itself -- so the two must stay in step. +produced = set() +for entry, controls in ((QWEN, BOTH), (ORNITH, THINK), (QWEN, THINK)): + for value, _ in plan.reasoning_options(entry, None, controls): + produced |= set(plan.reasoning_kwargs(value, entry, controls)) +check("the dashboard's knobs are exactly the ones taken from clients", + produced == set(plan.REASONING_KEYS), (sorted(produced), plan.REASONING_KEYS)) +check("both knobs are covered", set(plan.REASONING_KEYS) == {"enable_thinking", "reasoning_effort"}, + plan.REASONING_KEYS) print("\n5. the setting survives a setup re-run (`llmhost update`)") from llmhost import cli From c8f04f49b7401e1c5361c0439838f51e24258121 Mon Sep 17 00:00:00 2001 From: Neil Bantoc Date: Wed, 4 Nov 2026 00:23:33 -0800 Subject: [PATCH 03/10] Requests table: durations in h/m/s, and the seconds each phase took MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Duration, TTFT and the two new columns use one formatter that grows units only as the value reaches them: 142 ms, 7.52 s, 31.2 s, then 1m 20s, then 1h 02m 06s. Sub-minute values keep their old precision, which is where almost every request lives; a long generation no longer reads as "80.4 s". Prompt sec and Generated sec show the two phases the rates were already computed over, so a row now says where its time went: an 8011-token prompt as 19.3 s of prefill at 415 tok/s, then 6.74 s generating 141 tokens at 20.9. The seconds come from the same split as the rates beside them -- a test asserts tok/s == tokens / seconds for both phases, so the two can't drift apart. A request that didn't stream has no first-token mark and so no split: its prompt seconds read "—" and its whole duration is charged to generation, which the column subtitle now says rather than leaving to be inferred. run_phases/run_row move out of the snapshot closure to module level, so the suite exercises the real row-building instead of a copy of it that had to be kept in step by hand. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 5 +++++ llmhost/web/index.html | 28 ++++++++++++++++++++------- llmhost/web/server.py | 42 ++++++++++++++++++++++++----------------- tests/test_dashboard.py | 32 +++++++++++++++---------------- 4 files changed, 67 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 45b88ba..7b1744b 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,11 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac The dashboard (`http://.local:11340`) shows the active model, throughput, KV cache, GPU utilization, temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server. +It also lists the last 20 finished requests, each split into its two phases at the first generated token: +prompt tokens with the seconds and rate of the prefill, then generated tokens with the seconds and rate of +the generation. A request that didn't stream has no first-token mark, so its prompt seconds read `—` and its +whole duration counts as generation. + ## Connecting opencode **On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 5c9d53f..646aed6 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -244,8 +244,8 @@ pre { - - + + @@ -311,6 +311,15 @@ const fmt = { dur: (s) => { if (s == null) return ""; s = Math.floor(s); const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60); return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; }, secs: (v) => v == null ? "—" : v < 1 ? Math.round(v * 1000) + " ms" : v < 10 ? v.toFixed(2) + " s" : v.toFixed(1) + " s", + // A request's own clock: seconds while that reads precisely, then minutes and hours as + // it passes them -- never a unit the value hasn't reached. + span: (v) => { + if (v == null) return "—"; + if (v < 60) return fmt.secs(v); + const t = Math.round(v), h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60; + const pad = (n) => String(n).padStart(2, "0"); + return h ? `${h}h ${pad(m)}m ${pad(s)}s` : `${m}m ${pad(s)}s`; + }, ctx: (n) => n == null ? "" : n >= 1024 ? Math.round(n / 1024) + "k ctx" : n + " ctx", }; @@ -512,11 +521,13 @@ function renderRuns(s) { const tr = document.createElement("tr"); if (r.aborted) tr.className = "aborted"; cell(tr, clock(r.t)); - cell(tr, ...dash(r.dur, fmt.secs)); - cell(tr, ...dash(r.ttft, fmt.secs)); + cell(tr, ...dash(r.dur, fmt.span)); + cell(tr, ...dash(r.ttft, fmt.span)); cell(tr, ...dash(r.prompt, (v) => fmt.big(v))); + cell(tr, ...dash(r.prompt_s, fmt.span)); cell(tr, ...dash(r.prompt_tps, (v) => fmt.n(v, 0))); cell(tr, ...dash(r.gen, (v) => fmt.big(v))); + cell(tr, ...dash(r.gen_s, fmt.span)); cell(tr, ...dash(r.gen_tps, (v) => fmt.n(v, 1))); cell(tr, ...dash(r.kv_peak_pct, (v) => fmt.n(v, 1) + "%")); body.append(tr); @@ -529,15 +540,18 @@ function renderRuns(s) { const peak = Math.max(...runs.map((r) => r.kv_peak_pct ?? 0)); const tr = document.createElement("tr"); cell(tr, `${runs.length} shown`); - cell(tr, ...dash(avg("dur"), fmt.secs)); - cell(tr, ...dash(avg("ttft"), fmt.secs)); + cell(tr, ...dash(avg("dur"), fmt.span)); + cell(tr, ...dash(avg("ttft"), fmt.span)); cell(tr, ...dash(avg("prompt"), (v) => fmt.big(v))); + cell(tr, ...dash(avg("prompt_s"), fmt.span)); cell(tr, ...dash(avg("prompt_tps"), (v) => fmt.n(v, 0))); cell(tr, ...dash(avg("gen"), (v) => fmt.big(v))); + cell(tr, ...dash(avg("gen_s"), fmt.span)); cell(tr, ...dash(avg("gen_tps"), (v) => fmt.n(v, 1))); cell(tr, ...dash(peak > 0 ? peak : null, (v) => fmt.n(v, 1) + "%")); foot.append(tr); - $("runs-sub").textContent = "newest first · averages below · tok/s split at first token"; + $("runs-sub").textContent = "newest first · averages below · phases split at the first token; " + + "a request that didn't stream has none, so all of it counts as generation"; } const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 125d9e5..aec2489 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -94,6 +94,30 @@ def run_kv_peak(history, run, now, current): return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None +def run_phases(r): + """How long a run spent on each phase, and the rate of each. Time to first token + covers the prompt's prefill (queueing with it, there being nothing finer to measure + from), and what's left of the duration is generation; a rate over the whole duration + would blur the two together. + + A run that didn't stream has no first-token mark and so no split: its prompt time is + unknown and its whole duration is charged to generation -- which the table says, by + showing no prompt seconds beside it.""" + dur, ttft = r.get("dur") or 0, r.get("ttft") + prompt_s = ttft + gen_s = (dur - ttft) if (ttft is not None and dur > ttft) else dur + return {"prompt_s": prompt_s, "gen_s": gen_s or None, + "prompt_tps": (r["prompt"] / prompt_s) if (prompt_s and r.get("prompt")) else None, + "gen_tps": (r["gen"] / gen_s) if (gen_s and r.get("gen")) else None} + + +def run_row(r, kv_peak): + """One finished request as the dashboard's table wants it.""" + return {"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), + "prompt": r.get("prompt"), "ttft": r.get("ttft"), **run_phases(r), + "kv_peak_pct": kv_peak, "aborted": bool(r.get("aborted"))} + + def parse_vllm_metrics(text): vals = {} for line in text.splitlines(): @@ -227,15 +251,6 @@ class Sampler: def ratio(a, b): return shown[a] / shown[b] if shown.get(b) else None - def run_rates(r): - """Split a run into its two phases: time to first token covers the prefill, the - rest is generation. Rates over the whole duration would blur the two together.""" - dur, ttft = r.get("dur") or 0, r.get("ttft") - prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None - gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur - gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None - return gen_tps, prompt_tps - last_log = None if phase in ("loading", "failed"): lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)] @@ -254,14 +269,7 @@ class Sampler: if key in self._seen_runs or r.get("start") is None: continue self._seen_runs.add(key) - gen_tps, prompt_tps = run_rates(r) - self.runs.append({ - "t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), - "prompt": r.get("prompt"), "ttft": r.get("ttft"), - "gen_tps": gen_tps, "prompt_tps": prompt_tps, - "kv_peak_pct": run_kv_peak(self.history, r, now, point["kv"]), - "aborted": bool(r.get("aborted")), - }) + self.runs.append(run_row(r, run_kv_peak(self.history, r, now, point["kv"]))) if len(self._seen_runs) > 4 * RUNS_SHOWN: # The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the # oldest keys can't resurrect a run we already have. diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 39255f9..0b3bc7a 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -66,34 +66,27 @@ for t, kv in ((99.0, 10.0), (101.0, 40.0), (105.0, 72.5), (109.0, 55.0), (111.0, s.history.append({"t": t, "kv": kv, "gen": None, "prompt": None, "ttft": None, "util": None, "temp": None, "power": None}) point = {"t": 111.0, "kv": 90.0} -gen_tps, prompt_tps = (None, None) -# exercise the real merge code by calling the block through a tiny shim +# The merge loop's own bookkeeping, around the real run_row/run_kv_peak it calls. def merge(sampler, recent, point): - metrics = {"recent": recent} - def run_rates(r): - dur, ttft = r.get("dur") or 0, r.get("ttft") - p = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None - w = dur - ttft if (ttft is not None and dur > ttft) else dur - g = (r["gen"] / w) if (w and r.get("gen")) else None - return g, p - for r in metrics["recent"]: + for r in recent: key = (r.get("start"), r.get("end")) if key in sampler._seen_runs or r.get("start") is None: continue sampler._seen_runs.add(key) window = [q["kv"] for q in sampler.history if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]] - g, p = run_rates(r) - sampler.runs.append({"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), - "prompt": r.get("prompt"), "ttft": r.get("ttft"), - "gen_tps": g, "prompt_tps": p, - "kv_peak_pct": max(window) if window else point["kv"], - "aborted": bool(r.get("aborted"))}) + sampler.runs.append(web.run_row(r, max(window) if window else point["kv"])) merge(s, [run], point) r = s.runs[-1] +check("prompt seconds = time to first token", r["prompt_s"] == 2.0, r["prompt_s"]) +check("generated seconds = what's left of the duration", r["gen_s"] == 8.0, r["gen_s"]) +check("the two phases account for the whole run", r["prompt_s"] + r["gen_s"] == r["dur"], r) check("prompt tok/s = prompt / ttft", abs(r["prompt_tps"] - 7667 / 2.0) < 1e-6, r["prompt_tps"]) check("gen tok/s excludes the prefill", abs(r["gen_tps"] - 200 / 8.0) < 1e-6, r["gen_tps"]) +check("each rate matches the seconds shown next to it", + abs(r["prompt_tps"] - r["prompt"] / r["prompt_s"]) < 1e-9 + and abs(r["gen_tps"] - r["gen"] / r["gen_s"]) < 1e-9, r) check("peak KV from the run's own window", r["kv_peak_pct"] == 72.5, r["kv_peak_pct"]) check("points outside the window ignored", r["kv_peak_pct"] != 90.0) merge(s, [run], point) @@ -104,8 +97,15 @@ s2 = S() merge(s2, [{"start": 1.0, "end": 1.0, "dur": 0.0, "gen": 0, "prompt": 0, "ttft": None}], {"t": 1, "kv": None}) r2 = s2.runs[-1] check("no rates, no crash", r2["gen_tps"] is None and r2["prompt_tps"] is None, r2) +check("no seconds either, rather than a zero", r2["prompt_s"] is None and r2["gen_s"] is None, r2) merge(s2, [{"start": 2.0, "end": 3.0, "dur": 1.0, "gen": 5, "prompt": 9, "ttft": 1.0}], {"t": 3, "kv": None}) check("ttft == dur -> gen rate falls back to duration", s2.runs[-1]["gen_tps"] == 5.0, s2.runs[-1]) +check("...and the generated seconds say so too", s2.runs[-1]["gen_s"] == 1.0, s2.runs[-1]) +merge(s2, [{"start": 4.0, "end": 6.0, "dur": 2.0, "gen": 8, "prompt": 40, "ttft": None}], {"t": 6, "kv": None}) +nos = s2.runs[-1] +check("a run that didn't stream has no prompt seconds", nos["prompt_s"] is None, nos) +check("...no prompt rate to go with them", nos["prompt_tps"] is None, nos) +check("...and its whole duration counts as generation", nos["gen_s"] == 2.0 and nos["gen_tps"] == 4.0, nos) check("no KV history -> current value", s2.runs[-1]["kv_peak_pct"] is None) print("\n6. the broken-pipe traceback you saw collapses to one line") From d07a92e5b5d019036403833e52860c16d6b1c139 Mon Sep 17 00:00:00 2001 From: neil Date: Thu, 5 Nov 2026 01:29:45 -0800 Subject: [PATCH 04/10] Scrub real machine hostname from README and test fixtures --- README.md | 6 ++-- tests/test_opencode.py | 62 +++++++++++++++++++++--------------------- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 7b1744b..d7cf485 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ the file up as `opencode.json.before-llmhost`. A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead. **On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner -that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (popos.local)` +that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (mybox.local)` — under the provider id `llmhost-`. ### One opencode, several servers @@ -114,8 +114,8 @@ never overwritten (setup takes `llmhost-local` instead and says so), and `uninst provider — remote ones, and providers llm-host didn't create, are left in place. If a provider's default model goes away with it, `model` is repointed at a surviving llm-host provider, and dropped only if there is none. -Retiring a server is the one thing the servers can't do for each other: uninstalling on `popos` can't reach the -clients pointing at it. On each client, run `llmhost opencode-remove --host popos.local` (or delete the block by +Retiring a server is the one thing the servers can't do for each other: uninstalling on `mybox` can't reach the +clients pointing at it. On each client, run `llmhost opencode-remove --host mybox.local` (or delete the block by hand if llm-host isn't installed there). ### If opencode keeps asking for the API key diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 0f73e2d..048a0db 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -47,21 +47,21 @@ check("limits come from the loaded model", check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"]) print("\n2. local + remote side by side") -rp, rb = remote("popos.local") +rp, rb = remote("mybox.local") reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"}) st, path, prov, authcl = opencode.configure(CFG) d = load() -check("remote id is llmhost-popos", rp == "llmhost-popos", rp) -check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"]) +check("remote id is llmhost-mybox", rp == "llmhost-mybox", rp) +check('remote name is "LLMHost (mybox.local)"', rb["name"] == "LLMHost (mybox.local)", rb["name"]) check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"])) check("remote label names no model (it would go stale)", - rb["models"]["default"]["name"] == "Default model (popos.local)", rb["models"]["default"]["name"]) -check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"])) + rb["models"]["default"]["name"] == "Default model (mybox.local)", rb["models"]["default"]["name"]) +check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-mybox"], sorted(d["provider"])) check("remote untouched", d["provider"][rp] == rb) check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"]) print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)") -_, rb2 = remote("popos.local", prov="llmhost") +_, rb2 = remote("mybox.local", prov="llmhost") reset({"provider": {"llmhost": rb2}}) st, path, prov, authcl = opencode.configure(CFG) d = load() @@ -83,7 +83,7 @@ check("a stale default makes it an update", st == "updated", st) check("and it is migrated", load()["model"] == "mymac/default", load().get("model")) print("\n5. uninstall: remove local, keep remote, repoint model") -rp, rb = remote("popos.local") +rp, rb = remote("mybox.local") reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"}) st, path, removed, new_model = opencode.remove(local=True) d = load() @@ -108,13 +108,13 @@ check("remote still there", list(load()["provider"]) == [rp]) print("\n7. retiring a remote server (gap 3)") reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"}) -st, path, removed, new_model = opencode.remove(local=False, host="popos.local") +st, path, removed, new_model = opencode.remove(local=False, host="mybox.local") d = load() check("removed the remote", removed == [rp], removed) check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"])) check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model")) reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}}) -st, path, removed, _ = opencode.remove(local=False, host="popos") +st, path, removed, _ = opencode.remove(local=False, host="mybox") check("short hostname also matches", removed == [rp], removed) print("\n8. --all drops the model key when nothing is left") @@ -126,15 +126,15 @@ check("model key dropped", "model" not in d and new_model is None, d) check("provider key dropped", "provider" not in d, d) print("\n9. foreign providers are never touched") -foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (popos)", - "options": {"baseURL": "http://popos.local:1134/v1", "apiKey": "{file:~/.config/opencode/popos-vllm.key}"}, +foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (mybox)", + "options": {"baseURL": "http://mybox.local:1134/v1", "apiKey": "{file:~/.config/opencode/mybox-vllm.key}"}, "models": {"x": {"name": "x"}}} -reset({"provider": {"popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "popos-vllm/x"}) +reset({"provider": {"mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "mybox-vllm/x"}) st, path, removed, new_model = opencode.remove(local=True) d = load() check("only ours removed", removed == ["llmhost"], removed) -check("foreign intact", d["provider"]["popos-vllm"] == foreign) -check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model")) +check("foreign intact", d["provider"]["mybox-vllm"] == foreign) +check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model")) st, path, removed, _ = opencode.remove(local=False, every=True) check("--all skips foreign", removed == [], removed) @@ -165,15 +165,15 @@ st, path, prov, authcl = opencode.configure(CFG) check("still installs", prov == "llmhost" and st == "added", (prov, st)) print("\n13. --host must not take a foreign provider on the same host (regression)") -rp, rb = remote("popos.local") -reset({"provider": {rp: rb, "popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, - "model": "popos-vllm/x"}) -st, path, removed, new_model = opencode.remove(local=False, host="popos.local") +rp, rb = remote("mybox.local") +reset({"provider": {rp: rb, "mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)}, + "model": "mybox-vllm/x"}) +st, path, removed, new_model = opencode.remove(local=False, host="mybox.local") d = load() check("removed only ours", removed == [rp], removed) -check("foreign on same host survives", "popos-vllm" in d["provider"]) +check("foreign on same host survives", "mybox-vllm" in d["provider"]) check("local survives", "llmhost" in d["provider"]) -check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model")) +check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model")) print("\n14. a stale cached key is cleared on configure") def put_auth(d, mode=0o600): @@ -212,12 +212,12 @@ check("left verbatim", f.read_text() == "{ not json") check("reported nothing cleared", authcl is False, authcl) print("\n17. remove() takes the cached key with the provider") -reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-popos": remote("popos.local")[1]}}) -put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-popos": {"type": "api", "key": "sk-B"}}) +reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-mybox": remote("mybox.local")[1]}}) +put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-mybox": {"type": "api", "key": "sk-B"}}) st, path, removed, _ = opencode.remove(local=True) a = get_auth() check("local cred cleared", "llmhost" not in a, a) -check("remote cred kept", a.get("llmhost-popos") == {"type": "api", "key": "sk-B"}, a) +check("remote cred kept", a.get("llmhost-mybox") == {"type": "api", "key": "sk-B"}, a) print("\n18. purge --keep-key keeps the API key through a purge") from llmhost import cli @@ -276,9 +276,9 @@ print("\n21. sync() never wires opencode up on its own") reset() check("no config file -> no-op", opencode.sync(CFG) is None) check("still no config file", not opencode.config_file().exists()) -reset({"provider": {"popos-vllm": foreign}, "model": "popos-vllm/x"}) +reset({"provider": {"mybox-vllm": foreign}, "model": "mybox-vllm/x"}) check("no local block -> no-op", opencode.sync(CFG) is None) -check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign}) +check("foreign provider untouched", load()["provider"] == {"mybox-vllm": foreign}) reset({"provider": {"mymac": opencode.local_block(CFG)}}) check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac") @@ -286,8 +286,8 @@ check.section("22. a default naming a specific model is migrated to the alias") for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"), ("llmhost/ornith-1.5-9b", "llmhost/default"), ("llmhost/default", "llmhost/default"), - ("popos-vllm/qwen3.8-27b", "popos-vllm/qwen3.8-27b"), - ("llmhost-popos/qwen3.8-27b", "llmhost-popos/qwen3.8-27b")): + ("mybox-vllm/qwen3.8-27b", "mybox-vllm/qwen3.8-27b"), + ("llmhost-mybox/qwen3.8-27b", "llmhost-mybox/qwen3.8-27b")): reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model}) opencode.configure(CFG) got = load().get("model") @@ -301,10 +301,10 @@ import argparse, io, contextlib cli._service_check = lambda: CFG buf = io.StringIO() with contextlib.redirect_stdout(buf): - cli.cmd_opencode(argparse.Namespace(host="popos.local", provider=None, json=True)) + cli.cmd_opencode(argparse.Namespace(host="mybox.local", provider=None, json=True)) snip = json.loads(buf.getvalue()) prov_id, block = next(iter(snip["provider"].items())) -check("provider named after the host", prov_id == "llmhost-popos", prov_id) +check("provider named after the host", prov_id == "llmhost-mybox", prov_id) check("model is /", snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"], (snip["model"], list(block["models"]))) @@ -313,7 +313,7 @@ check.section("24. the block never offers a reasoning chooser of its own") check("opencode's whole menu is switched off", opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")}, opencode.effort_variants()) -q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local") +q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "mybox.local", "k", "mybox.local") ent = q["models"]["default"] check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent) check("but every effort level is disabled", @@ -322,7 +322,7 @@ check("no variant carries a reasoningEffort to send", not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"]) check("the model levels from the catalog are not offered either", not ({"xhigh"} & set(ent["variants"])), ent["variants"]) -nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local") +nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "mybox.local", "k", "mybox.local") check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"]) check("one entry only, named for the alias, so the client can't pick a model either", list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"])) From e814a2359dcd5207f7604d7b18108bf2408309c3 Mon Sep 17 00:00:00 2001 From: neil Date: Thu, 5 Nov 2026 21:44:09 -0800 Subject: [PATCH 05/10] install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt` is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt` shows the tunnel (and `logs -f` now follows the service it was asked for). Co-Authored-By: Claude Opus 5.5 --- README.md | 93 +++++++++++++- llmhost/cli.py | 178 +++++++++++++++++++++++++- llmhost/newt.py | 89 +++++++++++++ llmhost/paths.py | 26 ++++ llmhost/service.py | 13 +- llmhost/web/index.html | 58 +++++++-- llmhost/web/oidc.py | 236 +++++++++++++++++++++++++++++++++++ llmhost/web/server.py | 98 ++++++++++++++- tests/harness.py | 2 +- tests/test_dashboard_auth.py | 225 +++++++++++++++++++++++++++++++++ tests/test_newt.py | 163 ++++++++++++++++++++++++ 11 files changed, 1155 insertions(+), 26 deletions(-) create mode 100644 llmhost/newt.py create mode 100644 llmhost/web/oidc.py create mode 100644 tests/test_dashboard_auth.py create mode 100644 tests/test_newt.py diff --git a/README.md b/README.md index d7cf485..8f5bc98 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,11 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac | `llmhost switch ` | serve a different model (downloads it first if needed) | | `llmhost download ` | download ahead of time | | `llmhost watch` | download and loading progress, until the model is ready | -| `llmhost logs -f` | follow the model server log | +| `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 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) | @@ -67,6 +69,86 @@ prompt tokens with the seconds and rate of the prefill, then generated tokens wi the generation. A request that didn't stream has no first-token mark, so its prompt seconds read `—` and its 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 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. + +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: + +- a confidential client using `client_secret_basic` +- the authorization-code flow with PKCE (S256) +- scopes `openid profile email groups` +- the redirect URI `https:///auth/callback` + +Then: + +```bash +llmhost install-newt \ + --endpoint https://pangolin.example.com --newt-id \ + --public-url https://llm-dash.example.com \ + --issuer https://auth.example.com --client-id llm-host \ + --allow-group llm-admins # and/or --allow-user ; 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 | `:` | llm-host, through your OIDC provider | +| API, at a host of your choice | `:` | llm-host, with the API key | + +Clients then use `https:///v1` with the key from `llmhost key`. + +For Authelia, the client looks like this: + +```yaml +identity_providers: + oidc: + clients: + - client_id: llm-host + client_name: llm-host dashboard + client_secret: '$pbkdf2-sha512$...' # authelia crypto hash generate pbkdf2 --random + public: false + authorization_policy: two_factor + require_pkce: true + pkce_challenge_method: S256 + redirect_uris: ['https://llm-dash.example.com/auth/callback'] + scopes: [openid, profile, email, groups] + response_types: [code] + grant_types: [authorization_code] + token_endpoint_auth_method: client_secret_basic +``` + +How the dashboard's 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://.local:11340`) is sent there, because that's the only host the session cookie exists on. + +`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. + ## Connecting opencode **On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official @@ -204,6 +286,8 @@ python3 tests/test_opencode.py # or run one directly | `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache | | `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_reasoning.py` | effort options matching the real chat templates; the setting surviving an update | ## Continuing on an NVIDIA box @@ -248,6 +332,9 @@ 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/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 | | Linux: `~/.config/systemd/user/llm-host-{model,web}.service` | services (`journalctl --user -u llm-host-model`) | | macOS: `~/Library/LaunchAgents/dev.llm-host.{model,web}.plist` | services; logs in `~/Library/Logs/llm-host/` | @@ -262,4 +349,6 @@ On macOS the services are launchd agents, so they run while you're logged in. `reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's 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 expose them to the internet. +- 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. +- Everyone using the API shares one key, with no per-person revocation or rate limits. diff --git a/llmhost/cli.py b/llmhost/cli.py index 5ac5f00..5b274dc 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -117,7 +117,11 @@ def carried_settings(old, names): `llmhost update` would quietly put every model back to "Model default". Models that no longer fit lose their setting along with their plan.""" kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names} - return {"reasoning": kept} if kept else {} + out = {"reasoning": kept} if kept else {} + for k in ("newt", "dashboard_auth"): # set by `llmhost install-newt`, not by the plan + if old.get(k): + out[k] = old[k] + return out def cmd_setup(a): @@ -190,6 +194,10 @@ def cmd_setup(a): if not a.no_start: service.restart("web") service.restart("model") + if cfg.get("newt") and service.installed("newt"): + from . import newt + if newt.ensure_binary(say): + service.restart("newt") host = default_host() say(f""" Done. @@ -328,7 +336,7 @@ def _service_check(): def cmd_status(a): cfg = _service_check() host = default_host() - for name in service.NAMES: + for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)): st, up = service.state(name) upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else "" say(f"{name:6} {st}{upt}") @@ -340,6 +348,12 @@ def cmd_status(a): except Exception: say(f"active model {cfg['active']} is not answering yet") say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}") + d = cfg.get("dashboard_auth") or {} + if d.get("mode") == "oidc": + who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])]) + say(f"public {d['public_url']} (sign-in via {d['issuer']}; {who})") + if cfg.get("newt"): + say(f"tunnel newt -> {cfg['newt']['endpoint']}") def cmd_models(a): @@ -375,9 +389,10 @@ def cmd_ctl(a): def cmd_logs(a): _service_check() + name = "newt" if a.newt else "web" if a.web else "model" if a.follow: - os.execvp(service.log_command("model")[0], service.log_command("model")) - for line in service.logs("web" if a.web else "model", a.n): + os.execvp(service.log_command(name)[0], service.log_command(name)) + for line in service.logs(name, a.n): say(line) @@ -466,6 +481,139 @@ def cmd_key(a): say(paths.api_key()) +def _restart_if_running(name): + if service.state(name)[0] in ("active", "activating"): + if not service.restart(name): + say(f"Couldn't restart the {name} service; see `llmhost logs --{name}`.") + + +def lan_ip(): + """This machine's address on its default route -- what newt, running here, should dial + to reach the services. Connecting a UDP socket sends nothing.""" + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + s.connect(("192.0.2.1", 9)) # TEST-NET-1: never routed anywhere + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + finally: + s.close() + + +def _ask(label, given, default=None, flag=None, secret=False, env=None): + """A value from its flag, its env var, or a prompt (keeping `default` on Enter). + Without a terminal, a value that's still missing is an error naming the flag.""" + if given: + return given + if env and os.environ.get(env): + return os.environ[env] + if not sys.stdin.isatty(): + if default: + return default + sys.exit(f"missing {flag or ('$' + env)}" + (f" (or ${env})" if flag and env else "")) + hint = " [keep current]" if secret and default else (f" [{default}]" if default else "") + if secret: + import getpass + v = getpass.getpass(f"{label}{hint}: ").strip() + else: + v = input(f"{label}{hint}: ").strip() + v = v or default + if not v: + sys.exit(f"{label} is required") + return v + + +def _check_url(label, url, bare=True): + import urllib.parse + u = urllib.parse.urlsplit(url) + if u.scheme not in ("http", "https") or not u.netloc or (bare and u.path.strip("/")): + sys.exit(f"{label} should look like https://host.example.com, not {url!r}") + if u.scheme != "https": + sys.exit(f"{label} must be https:// -- this is the address people reach from the internet") + return url.rstrip("/") + + +def cmd_install_newt(a): + """Upgrade a LAN install for the internet: newt tunnel + OIDC sign-in on the dashboard.""" + from . import newt + from .web import oidc + cfg = _service_check() + old_n, old_d = cfg.get("newt") or {}, cfg.get("dashboard_auth") or {} + newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for + + say("Pangolin site (Pangolin: Sites -> Add Site -> Newt):") + endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint", a.endpoint, old_n.get("endpoint"), "--endpoint")) + site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id") + have_newt_secret = paths.NEWT_SECRET_FILE.exists() and old_n + newt_secret = _ask(" Newt secret", None, "keep" if have_newt_secret else None, secret=True, env="LLMHOST_NEWT_SECRET") + + say("\nDashboard sign-in (an OIDC client registered with your provider):") + public_url = _check_url("Dashboard URL", _ask(" Dashboard's public URL", a.public_url, old_d.get("public_url"), "--public-url")) + issuer = _check_url("Issuer", _ask(" OIDC issuer", a.issuer, old_d.get("issuer"), "--issuer"), bare=False) + client_id = _ask(" Client ID", a.client_id, old_d.get("client_id") or "llm-host", "--client-id") + have_oidc_secret = paths.OIDC_SECRET_FILE.exists() and old_d + oidc_secret = _ask(" Client secret", None, "keep" if have_oidc_secret else None, secret=True, env="LLMHOST_OIDC_SECRET") + groups, users = a.allow_group or [], a.allow_user or [] + if not (groups or users): + # A re-run keeps the allow list unless it's given again. + groups, users = old_d.get("allowed_groups", []), old_d.get("allowed_users", []) + if not (groups or users): + groups = [g.strip() for g in _ask(" Groups allowed in (comma-separated)", None, None, + "--allow-group").split(",") if g.strip()] + if not (groups or users): + sys.exit("say who may sign in: --allow-group and/or --allow-user ") + + dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url, + "allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))} + secret_for_check = paths.oidc_secret() if oidc_secret == "keep" else oidc_secret + try: + oidc.OIDC(dash, secret_for_check).discovery() + except oidc.AuthError as e: + sys.exit(str(e)) + + newt.ensure_binary(say) + if newt_secret != "keep": + paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret) + if oidc_secret != "keep": + paths.save_secret(paths.OIDC_SECRET_FILE, oidc_secret) + cfg["newt"] = {"endpoint": endpoint, "id": site_id} + cfg["dashboard_auth"] = dash + paths.save_config(cfg) + + service.install("newt") + if not service.restart("newt"): + say("newt didn't start; see `llmhost logs --newt`.") + _restart_if_running("web") + ip = lan_ip() + say(f""" +Done. newt is running and the dashboard now signs in through {issuer}; +the API key no longer opens it (the API itself still uses the key). + +In Pangolin, add two HTTP resources on this site, with Pangolin's own SSO off on both +(llm-host checks the API key on one and signs people in on the other): + dashboard {public_url} -> http://{ip}:{cfg['web_port']} + API -> http://{ip}:{cfg['api_port']} +Point them at {ip}, not localhost: requests from localhost count as local here. + +Register this redirect URI with your OIDC client: {public_url}/auth/callback +Clients use https:///v1 with the API key (`llmhost key`). +Undo all of this with: llmhost remove-newt""") + + +def cmd_remove_newt(a): + """Back to a LAN-only install: stop newt, and the dashboard takes the API key again.""" + cfg = _service_check() + if service.installed("newt"): + service.uninstall("newt") + shutil.rmtree(paths.NEWT_DIR, ignore_errors=True) + paths.NEWT_SECRET_FILE.unlink(missing_ok=True) + paths.OIDC_SECRET_FILE.unlink(missing_ok=True) + had = bool(cfg.pop("newt", None)) | bool(cfg.pop("dashboard_auth", None)) + paths.save_config(cfg) + _restart_if_running("web") + say("Removed newt; the dashboard takes the API key again." if had else "newt wasn't installed.") + + def cmd_download(a): cfg = _service_check() m = next((x for x in cfg["models"] if x["name"] == a.model), None) @@ -554,7 +702,7 @@ def cmd_uninstall(a): # Read the catalog now: --purge deletes it along with the rest of llm-host. cached = cached_catalog_models() cfg = paths.load_config() or {} - for name in service.NAMES: + for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)): service.uninstall(name) # Stopping returns before the processes have exited (launchd especially). Wait, so a # reinstall right after this finds the ports free instead of moving to other ones. @@ -563,7 +711,7 @@ def cmd_uninstall(a): ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else []) with Spinner("Waiting for the services to exit"): wait_ports_free(ours, timeout=30) - for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"): + for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test", "newt"): shutil.rmtree(paths.DATA / d, ignore_errors=True) say("Removed services and backend environments.") # Before the --purge below: the provider is identified by its reference to KEY_FILE. @@ -637,6 +785,11 @@ def cmd_run_model(a): mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1)) +def cmd_run_newt(a): + from . import newt + newt.run() + + def cmd_run_web(a): _service_check() service.trim_log("web") @@ -679,10 +832,22 @@ def main(argv=None): s.add_argument("-f", "--follow", action="store_true") s.add_argument("-n", type=int, default=100) s.add_argument("--web", action="store_true", help="dashboard logs instead") + s.add_argument("--newt", action="store_true", help="tunnel logs instead") s.set_defaults(fn=cmd_logs) sub.add_parser("watch", help="show download and loading progress until the model is ready" ).set_defaults(fn=cmd_watch) sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key) + s = sub.add_parser("install-newt", help="reach this server from the internet: newt tunnel + OIDC sign-in on the dashboard") + s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com") + s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)") + s.add_argument("--public-url", help="the dashboard's public address, e.g. https://llm-dash.example.com") + s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com") + s.add_argument("--client-id", help="OIDC client ID (default llm-host; secret: prompted, or $LLMHOST_OIDC_SECRET)") + s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed into the dashboard (repeatable)") + s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed into the dashboard (repeatable)") + s.set_defaults(fn=cmd_install_newt) + sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel, dashboard back to the API key" + ).set_defaults(fn=cmd_remove_newt) s = sub.add_parser("download", help="download a model ahead of time") s.add_argument("model") s.set_defaults(fn=cmd_download) @@ -710,6 +875,7 @@ def main(argv=None): s.set_defaults(fn=cmd_uninstall) sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-web").set_defaults(fn=cmd_run_web) + sub.add_parser("run-newt").set_defaults(fn=cmd_run_newt) a = ap.parse_args(argv) a.fn(a) diff --git a/llmhost/newt.py b/llmhost/newt.py new file mode 100644 index 0000000..5674f88 --- /dev/null +++ b/llmhost/newt.py @@ -0,0 +1,89 @@ +"""Optional internet access through a Pangolin tunnel (newt). Stdlib only. + +`llmhost install-newt` is the upgrade path from a LAN install. It + - downloads a pinned newt release and checks it against the sha256 below, + - runs it as a third user service ("newt", via `llmhost run-newt`), which dials out to + the Pangolin server -- nothing on this machine is opened to the internet, + - and switches the dashboard to OIDC sign-in (web/oidc.py), because once it's public the + API key is too much power to hand out: it also stops and switches the model. + +newt runs in userspace (no root, no kernel WireGuard). Its site secret is kept in +~/.config/llm-host/newt_secret (0600) and handed over in its environment at start, never +written into the service file. +""" +import hashlib +import os +import platform +import tempfile +import urllib.request + +from . import paths + +VERSION = "1.19.0" +# From the GitHub release's asset digests for VERSION. +SHA256 = { + "linux_amd64": "6d40e223fa49d8bcfa9b7094208c58ff616997979bff7c884d0af61fcc1c5376", + "linux_arm64": "2a282e3edda7be17f092ac58aff0ec6dac9ddd152a642e8e61e6d625f2abe696", + "darwin_arm64": "bdc93f811e017affb893eab8d924dfe72ea63e1bdeaf85decec1afb711288ee5", + "darwin_amd64": "d44a4fd5526174788622e4eebea55ef268df19c85fc67766d0f27e23eb8800fa", +} +URL = "https://github.com/fosrl/newt/releases/download/{version}/newt_{plat}" + + +def platform_tag() -> str: + os_name = {"Linux": "linux", "Darwin": "darwin"}.get(platform.system()) + arch = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower()) + tag = f"{os_name}_{arch}" + if tag not in SHA256: + raise SystemExit(f"newt isn't packaged here for {platform.system()} {platform.machine()}") + return tag + + +def binary() -> "os.PathLike": + return paths.NEWT_DIR / "newt" + + +def installed_version(): + try: + return (paths.NEWT_DIR / "VERSION").read_text().strip() + except OSError: + return None + + +def ensure_binary(say=print, fetch=None) -> bool: + """Install the pinned newt if it isn't there already. Returns True if it changed.""" + if installed_version() == VERSION and binary().exists(): + return False + tag = platform_tag() + url = URL.format(version=VERSION, plat=tag) + say(f"Downloading newt {VERSION} ({tag})…") + data = (fetch or _fetch)(url) + got = hashlib.sha256(data).hexdigest() + if got != SHA256[tag]: + raise SystemExit(f"newt download didn't match its checksum (got {got}); not installing it") + paths.NEWT_DIR.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=paths.NEWT_DIR, prefix=".newt.") + with os.fdopen(fd, "wb") as f: + f.write(data) + os.chmod(tmp, 0o755) + os.replace(tmp, binary()) + (paths.NEWT_DIR / "VERSION").write_text(VERSION + "\n") + return True + + +def _fetch(url) -> bytes: + with urllib.request.urlopen(url, timeout=300) as r: + return r.read() + + +def run(): + """The service's entry point: exec newt with its credentials in the environment.""" + cfg = paths.load_config() + conf = cfg.get("newt") or {} + if not conf.get("endpoint") or not conf.get("id"): + raise SystemExit("newt isn't configured; run `llmhost install-newt`") + secret = paths.read_secret(paths.NEWT_SECRET_FILE, "newt site secret", "llmhost install-newt") + env = {**os.environ, "PANGOLIN_ENDPOINT": conf["endpoint"], "NEWT_ID": conf["id"], + "NEWT_SECRET": secret, "LOG_LEVEL": conf.get("log_level", "INFO")} + exe = str(binary()) + os.execve(exe, [exe], env) diff --git a/llmhost/paths.py b/llmhost/paths.py index 9c92785..dce29b1 100644 --- a/llmhost/paths.py +++ b/llmhost/paths.py @@ -6,6 +6,9 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG): ~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA) ~/.config/llm-host/config.json plan + settings ~/.config/llm-host/api_key API key (0600) + ~/.local/share/llm-host/newt newt binary, after `llmhost install-newt` + ~/.config/llm-host/oidc_secret dashboard sign-in client secret (0600), after install-newt + ~/.config/llm-host/newt_secret Pangolin site secret (0600), after install-newt """ import json import os @@ -21,6 +24,9 @@ DATA = Path(os.environ.get("LLMHOST_HOME", HOME / ".local/share/llm-host")) CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host")) CONFIG_FILE = CONFIG_DIR / "config.json" KEY_FILE = CONFIG_DIR / "api_key" +OIDC_SECRET_FILE = CONFIG_DIR / "oidc_secret" +NEWT_SECRET_FILE = CONFIG_DIR / "newt_secret" +NEWT_DIR = DATA / "newt" LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs") BIN_DIR = HOME / ".local/bin" SHIM = BIN_DIR / "llmhost" @@ -66,3 +72,23 @@ def api_key(create: bool = False) -> str: with os.fdopen(fd, "w") as f: f.write(key + "\n") return key + + + +def read_secret(path, what, fix) -> str: + try: + return path.read_text().strip() + except OSError: + raise SystemExit(f"No {what} at {path}; run `{fix}` again.") + + +def save_secret(path, secret: str) -> None: + CONFIG_DIR.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + f.write(secret + "\n") + os.chmod(path, 0o600) # O_CREAT's mode doesn't apply to a file that already existed + + +def oidc_secret() -> str: + return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-newt") diff --git a/llmhost/service.py b/llmhost/service.py index be7e50e..0992636 100644 --- a/llmhost/service.py +++ b/llmhost/service.py @@ -1,6 +1,7 @@ """Background services: systemd --user on Linux, launchd agents on macOS. -Two services: "model" (the inference server) and "web" (dashboard). Both run `llmhost run-`. +Two services: "model" (the inference server) and "web" (dashboard), plus "newt" (the +Pangolin tunnel) only after `llmhost install-newt`. Each runs `llmhost run-`. """ import os import re @@ -10,7 +11,8 @@ from pathlib import Path from . import paths -NAMES = ("model", "web") +NAMES = ("model", "web") # what setup installs +OPTIONAL = ("newt",) # installed by their own command def _run(cmd, timeout=60): @@ -32,7 +34,8 @@ def _unit_path(name): def _systemd_install(name): - desc = {"model": "llm-host model server", "web": "llm-host dashboard"}[name] + desc = {"model": "llm-host model server", "web": "llm-host dashboard", + "newt": "llm-host tunnel (newt)"}[name] extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else "" p = _unit_path(name) p.parent.mkdir(parents=True, exist_ok=True) @@ -104,6 +107,10 @@ def install(name): _run(["systemctl", "--user", "enable", _unit(name)]) +def installed(name): + return (_plist_path(name) if paths.IS_MAC else _unit_path(name)).exists() + + def enable_linger(): """Keep user services running without a login session (Linux). Often allowed without sudo.""" if paths.IS_MAC: diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 646aed6..bb3f75e 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -76,13 +76,14 @@ button.small { font-size: 12px; padding: 4px 10px; } } .effort select:disabled { color: var(--muted); } .effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; } -button { +button, a.btn { font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer; border: 1px solid var(--border); background: var(--panel-2); color: var(--text); } button:hover:not(:disabled) { border-color: var(--faint); } button:disabled { opacity: .45; cursor: default; } -button.primary { background: var(--accent); border-color: var(--accent); color: #fff; } +a.btn { display: inline-block; text-decoration: none; } +button.primary, a.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; } button.danger { color: var(--bad); } .profiles { display: flex; flex-direction: column; gap: 8px; } @@ -169,6 +170,7 @@ pre { … + @@ -268,6 +270,11 @@ pre {
+
@@ -275,6 +282,9 @@ pre { const $ = (id) => document.getElementById(id); let KEY = null; try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {} +// "key": the API key, typed in and kept in this browser. "oidc": a session cookie set by +// signing in at the provider (/auth/login); the key isn't accepted then. +let AUTH = { mode: "key" }; let state = null; let logTimer = null; @@ -287,14 +297,23 @@ function toast(msg) { } async function api(path, opts = {}) { - const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } }); - if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); } + const headers = { "Content-Type": "application/json" }; + if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY; + const r = await fetch(path, { ...opts, headers, credentials: "same-origin" }); + if (r.status === 401) { showAuth(AUTH.mode === "key" ? "That key was rejected." : ""); throw new Error("unauthorized"); } const body = await r.json(); if (!r.ok) throw new Error(body.error || r.statusText); return body; } -function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); } +function showAuth(err = "") { + if (AUTH.mode === "oidc") { + $("auth-form").hidden = true; $("auth-oidc").hidden = false; + $("auth").classList.add("show"); $("auth-oidc-go").focus(); + return; + } + $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); +} $("auth-form").addEventListener("submit", (e) => { e.preventDefault(); KEY = $("auth-key").value.trim(); @@ -302,7 +321,14 @@ $("auth-form").addEventListener("submit", (e) => { $("auth").classList.remove("show"); poll(); }); -$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); }; +$("logout").onclick = async () => { + if (AUTH.mode === "oidc") { + try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {} + AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); showAuth(); + return; + } + try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); +}; const fmt = { n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }), @@ -692,12 +718,26 @@ $("logs").addEventListener("toggle", () => { let pollTimer = null; async function poll() { clearTimeout(pollTimer); - if (!KEY) { showAuth(); return; } + if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; } try { render(await api("/api/status")); } - catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } } + catch (e) { + if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in + if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } + } pollTimer = setTimeout(poll, 2000); } -poll(); + +(async () => { + try { + const r = await fetch("/auth/config", { credentials: "same-origin" }); + if (r.ok) AUTH = await r.json(); + } catch (e) {} + if (AUTH.mode === "oidc") { + $("logout").title = "Sign out of this dashboard"; + if (AUTH.user) { $("whoami").textContent = AUTH.name || AUTH.user; $("whoami").hidden = false; } + } + poll(); +})(); diff --git a/llmhost/web/oidc.py b/llmhost/web/oidc.py new file mode 100644 index 0000000..e2ac810 --- /dev/null +++ b/llmhost/web/oidc.py @@ -0,0 +1,236 @@ +"""Dashboard sign-in through an OpenID Connect provider. Stdlib only. + +Off unless config.json has a "dashboard_auth" block with mode "oidc" (`llmhost install-newt` sets it); then it replaces the +API key on the dashboard (the API on api_port still takes the key -- that's for clients). + +The flow is the authorization-code flow of a confidential client, with PKCE: + + /auth/login -> 302 to the provider, with state, nonce and an S256 code challenge. + The state is also set in a short-lived cookie, so a callback only + completes in the browser that started it (no login CSRF). + /auth/callback -> code exchanged at the token endpoint with the client secret, the + ID token's claims checked, groups read from userinfo, the allow + list applied, and a session cookie set. + /auth/logout -> POST; drops the session. + +The ID token comes straight from the token endpoint over TLS, which OIDC Core 3.1.3.7 lets +a client rely on in place of checking its signature; its iss/aud/azp/exp/nonce are still +checked. Sessions live in memory, so a dashboard restart signs everyone out. +""" +import base64 +import hashlib +import hmac +import json +import secrets +import threading +import time +import urllib.error +import urllib.parse +import urllib.request + +SESSION_COOKIE = "llmhost_session" +STATE_COOKIE = "llmhost_oidc_state" +SESSION_TTL = 12 * 3600 +LOGIN_TTL = 600 # how long a started sign-in may take to come back +MAX_PENDING = 256 # unfinished sign-ins kept at once +CLOCK_SKEW = 120 +SCOPES = "openid profile email groups" + + +class AuthError(Exception): + """A sign-in that can't complete; the message is safe to show the user.""" + + +def b64url(raw: bytes) -> str: + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() + + +def jwt_claims(token: str) -> dict: + try: + payload = token.split(".")[1] + return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + except (IndexError, ValueError): + raise AuthError("the provider sent an unreadable ID token") + + +def parse_cookies(header: str) -> dict: + out = {} + for part in (header or "").split(";"): + k, sep, v = part.strip().partition("=") + if sep: + out.setdefault(k, v) + return out + + +def origin_of(url: str) -> str: + u = urllib.parse.urlsplit(url) + return f"{u.scheme}://{u.netloc}".lower() + + +class OIDC: + def __init__(self, conf: dict, client_secret: str, http=None): + self.issuer = conf["issuer"].rstrip("/") + self.client_id = conf["client_id"] + self.secret = client_secret + self.public_url = conf["public_url"].rstrip("/") + self.redirect_uri = self.public_url + "/auth/callback" + self.origin = origin_of(self.public_url) + self.secure = self.public_url.startswith("https://") + self.allowed_groups = set(conf.get("allowed_groups") or []) + self.allowed_users = set(conf.get("allowed_users") or []) + if not (self.allowed_groups or self.allowed_users): + raise ValueError("dashboard_auth needs allowed_groups or allowed_users") + self.http = http or self._http + self.lock = threading.Lock() + self.pending = {} # state -> {nonce, verifier, t} + self.sessions = {} # sha256(session id) -> {user, name, exp} + self._disco = None + + # -- provider --------------------------------------------------------------------- + + @staticmethod + def _http(method, url, data=None, headers=None): + req = urllib.request.Request(url, data=data, method=method, headers=headers or {}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + return r.status, r.read() + except urllib.error.HTTPError as e: + return e.code, e.read() + + def discovery(self) -> dict: + if self._disco is None: + try: + st, body = self.http("GET", self.issuer + "/.well-known/openid-configuration") + d = json.loads(body) if st == 200 else None + except (OSError, ValueError): + d = None + if not d or d.get("issuer", "").rstrip("/") != self.issuer: + raise AuthError(f"couldn't reach the sign-in provider at {self.issuer}") + self._disco = d + return self._disco + + # -- sign-in ---------------------------------------------------------------------- + + def start(self): + """Begin a sign-in: (provider URL to redirect to, state for the state cookie).""" + d = self.discovery() + state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3)) + now = time.time() + with self.lock: + for s in [s for s, p in self.pending.items() if now - p["t"] > LOGIN_TTL]: + del self.pending[s] + if len(self.pending) >= MAX_PENDING: + del self.pending[min(self.pending, key=lambda s: self.pending[s]["t"])] + self.pending[state] = {"nonce": nonce, "verifier": verifier, "t": now} + q = urllib.parse.urlencode({ + "response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri, + "scope": SCOPES, "state": state, "nonce": nonce, + "code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()), + "code_challenge_method": "S256"}) + return f"{d['authorization_endpoint']}?{q}", state + + def finish(self, params: dict, cookie_state: str) -> dict: + """Complete a sign-in from the callback's query. Returns the new session + {"id", "user", "name"}; raises AuthError for anything that doesn't check out.""" + if params.get("error"): + raise AuthError(f"the provider said: {params.get('error_description') or params['error']}") + state = params.get("state", "") + if not state or not cookie_state or not hmac.compare_digest(state, cookie_state): + raise AuthError("this sign-in was started in a different browser or tab; try again") + with self.lock: + p = self.pending.pop(state, None) + if not p or time.time() - p["t"] > LOGIN_TTL: + raise AuthError("this sign-in expired; try again") + d = self.discovery() + if "iss" in params and params["iss"].rstrip("/") != self.issuer: + raise AuthError("the response came from a different provider") + code = params.get("code") + if not code: + raise AuthError("the provider sent no authorization code") + + basic = base64.b64encode(f"{urllib.parse.quote(self.client_id, safe='')}:" + f"{urllib.parse.quote(self.secret, safe='')}".encode()).decode() + st, body = self.http("POST", d["token_endpoint"], urllib.parse.urlencode({ + "grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri, + "code_verifier": p["verifier"]}).encode(), { + "Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded", + "Accept": "application/json"}) + try: + tok = json.loads(body) + except ValueError: + tok = {} + if st != 200 or "id_token" not in tok: + raise AuthError(f"the provider refused the code ({tok.get('error') or st})") + + c = jwt_claims(tok["id_token"]) + now = time.time() + aud = c.get("aud") + auds = aud if isinstance(aud, list) else [aud] + if c.get("iss", "").rstrip("/") != self.issuer: + raise AuthError("the ID token is from a different provider") + if self.client_id not in auds or (len(auds) > 1 and c.get("azp") != self.client_id): + raise AuthError("the ID token was issued to a different client") + if not isinstance(c.get("exp"), (int, float)) or c["exp"] < now - CLOCK_SKEW: + raise AuthError("the ID token has expired") + if not hmac.compare_digest(str(c.get("nonce", "")), p["nonce"]): + raise AuthError("the ID token doesn't belong to this sign-in") + + info = dict(c) + if d.get("userinfo_endpoint") and tok.get("access_token"): + st, body = self.http("GET", d["userinfo_endpoint"], None, { + "Authorization": f"Bearer {tok['access_token']}", "Accept": "application/json"}) + try: + u = json.loads(body) if st == 200 else {} + except ValueError: + u = {} # a signed/encrypted userinfo isn't JSON; the ID token's claims stand + if u.get("sub") == c.get("sub"): + info.update(u) + + user = info.get("preferred_username") or info.get("email") or info.get("sub") + groups = set(info.get("groups") or []) + if user not in self.allowed_users and not (groups & self.allowed_groups): + raise AuthError(f"signed in as {user}, but that account isn't allowed on this dashboard") + + sid = secrets.token_urlsafe(32) + with self.lock: + for h in [h for h, s in self.sessions.items() if s["exp"] < now]: + del self.sessions[h] + self.sessions[self._h(sid)] = {"user": user, "name": info.get("name") or user, + "exp": now + SESSION_TTL} + return {"id": sid, "user": user, "name": info.get("name") or user} + + # -- sessions --------------------------------------------------------------------- + + @staticmethod + def _h(sid: str) -> str: + return hashlib.sha256(sid.encode()).hexdigest() + + def session(self, cookie_header: str): + sid = parse_cookies(cookie_header).get(SESSION_COOKIE) + if not sid: + return None + with self.lock: + s = self.sessions.get(self._h(sid)) + if s and s["exp"] < time.time(): + del self.sessions[self._h(sid)] + s = None + return s + + def end(self, cookie_header: str): + sid = parse_cookies(cookie_header).get(SESSION_COOKIE) + if sid: + with self.lock: + self.sessions.pop(self._h(sid), None) + + def same_origin(self, headers) -> bool: + """For state-changing requests: the browser's Origin (or Referer) must be the + dashboard's own. SameSite=Lax already keeps the cookie off cross-site POSTs; + this is the second lock on that door.""" + o = headers.get("Origin") or (origin_of(headers["Referer"]) if headers.get("Referer") else "") + return o.lower() == self.origin + + def cookie(self, name, value, max_age, path="/"): + attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"] + if self.secure: + attrs.append("Secure") + return "; ".join(attrs) diff --git a/llmhost/web/server.py b/llmhost/web/server.py index aec2489..ccab113 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -1,19 +1,23 @@ """Dashboard: status, metrics and model switching. Stdlib only. -Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key. +Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or, +when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py). """ import hmac +import html import json import re import socket import threading import time +import urllib.parse import urllib.request from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from .. import hfcache, hw, opencode, paths, plan, service +from . import oidc as oidc_mod HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 @@ -408,7 +412,7 @@ class Sampler: threading.Thread(target=fn, args=("model",), daemon=True).start() -def make_handler(sampler, key): +def make_handler(sampler, key, oidc=None): class Handler(BaseHTTPRequestHandler): server_version = "llm-host" @@ -425,6 +429,15 @@ def make_handler(sampler, key): self.wfile.write(body) def authed(self): + if oidc: + # Signed in through the provider; the API key isn't accepted here. + if oidc.session(self.headers.get("Cookie", "")) is None: + self.send_json(401, {"error": "unauthorized", "login": "/auth/login"}) + return False + if self.command == "POST" and not oidc.same_origin(self.headers): + self.send_json(403, {"error": "cross-origin request refused"}) + return False + return True h = self.headers.get("Authorization", "") tok = h[7:] if h.startswith("Bearer ") else "" if hmac.compare_digest(tok.encode(), key.encode()): @@ -432,8 +445,67 @@ def make_handler(sampler, key): self.send_json(401, {"error": "unauthorized"}) return False + def redirect(self, url, cookies=()): + self.send_response(302) + self.send_header("Location", url) + self.send_header("Cache-Control", "no-store") + for c in cookies: + self.send_header("Set-Cookie", c) + self.send_header("Content-Length", "0") + self.end_headers() + + def auth_page(self, code, msg): + body = (f"" + f"llm-host sign-in

Couldn't sign you in

{html.escape(msg)}

" + f"

Try again

").encode() + self.send_response(code) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Cache-Control", "no-store") + self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def on_public_host(self): + """A session cookie only exists on the public URL's host, so a visit by any + other name (mybox.local:11340) is sent there instead of to a login loop.""" + host = (self.headers.get("Host") or "").lower() + return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower() + + def auth_get(self, path, query): + if path == "/auth/config": + s = oidc.session(self.headers.get("Cookie", "")) if oidc else None + return self.send_json(200, {"mode": "oidc" if oidc else "key", + "user": s and s["user"], "name": s and s["name"]}) + if not oidc: + return self.send_json(404, {"error": "not found"}) + if path == "/auth/login": + if not self.on_public_host(): + return self.redirect(oidc.public_url + "/auth/login") + try: + url, state = oidc.start() + except oidc_mod.AuthError as e: + return self.auth_page(502, str(e)) + return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")]) + if path == "/auth/callback": + params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()} + cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "") + try: + s = oidc.finish(params, cookie_state) + except oidc_mod.AuthError as e: + return self.auth_page(403, str(e)) + print(f"llm-host dashboard: {s['user']} signed in", flush=True) + return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL), + oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")]) + self.send_json(404, {"error": "not found"}) + def do_GET(self): - path = self.path.split("?", 1)[0] + path, _, query = self.path.partition("?") + if path.startswith("/auth/"): + return self.auth_get(path, query) + if oidc and path in ("/", "/index.html") and not self.on_public_host(): + return self.redirect(oidc.public_url + "/") if path in ("/", "/index.html"): body = (HERE / "index.html").read_bytes() self.send_response(200) @@ -455,6 +527,17 @@ def make_handler(sampler, key): def do_POST(self): path = self.path.split("?", 1)[0] + if path == "/auth/logout" and oidc: + if not oidc.same_origin(self.headers): + return self.send_json(403, {"error": "cross-origin request refused"}) + oidc.end(self.headers.get("Cookie", "")) + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0)) + self.send_header("Content-Length", "11") + self.end_headers() + self.wfile.write(b'{"ok": true}') + return if not self.authed(): return try: @@ -494,6 +577,11 @@ def serve(): key = paths.api_key() sampler = Sampler(cfg, key) threading.Thread(target=sampler.loop, daemon=True).start() - srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key)) - print(f"llm-host dashboard on :{cfg['web_port']}", flush=True) + auth = None + conf = cfg.get("dashboard_auth") or {} + if conf.get("mode") == "oidc": + auth = oidc_mod.OIDC(conf, paths.oidc_secret()) + srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth)) + how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key" + print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True) srv.serve_forever() diff --git a/tests/harness.py b/tests/harness.py index 5875fcc..5d044e9 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -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", "BIN_DIR", "SHIM", "LOG_DIR"): + for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_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}") diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.py new file mode 100644 index 0000000..d5f8930 --- /dev/null +++ b/tests/test_dashboard_auth.py @@ -0,0 +1,225 @@ +"""Dashboard sign-in: API key mode, and OIDC against a fake provider, through the real handler.""" +import base64 +import hashlib +import http.client +import json +import sys +import threading +import urllib.parse +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 cli, paths +from llmhost.web import oidc as oidc_mod +from llmhost.web import server as web + +harness.guard(paths, ROOT) +check = harness.Checks() + +ISSUER = "https://auth.example.test" +PUBLIC = "https://dash.example.test" +KEY = "sk-test" + + +def b64(obj): + return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode() + + +class FakeProvider: + """Discovery, token and userinfo endpoints. The test sets what the next token + response's claims and userinfo look like.""" + def __init__(self): + self.claims = {} + self.userinfo = {} + self.challenges = {} # code -> code_challenge + self.token_calls = 0 + + def __call__(self, method, url, data=None, headers=None): + if url == ISSUER + "/.well-known/openid-configuration": + return 200, json.dumps({ + "issuer": ISSUER, "authorization_endpoint": ISSUER + "/authorize", + "token_endpoint": ISSUER + "/token", "userinfo_endpoint": ISSUER + "/userinfo"}).encode() + if url == ISSUER + "/token": + self.token_calls += 1 + form = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode()).items()} + want = "Basic " + base64.b64encode(b"llm-host:s3cret").decode() + if headers.get("Authorization") != want: + return 401, b'{"error": "invalid_client"}' + verifier = form.get("code_verifier", "") + challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() + if self.challenges.get(form.get("code")) != challenge: + return 400, b'{"error": "invalid_grant"}' + if form.get("redirect_uri") != PUBLIC + "/auth/callback": + return 400, b'{"error": "invalid_grant"}' + return 200, json.dumps({"id_token": f"h.{b64(self.claims)}.sig", "access_token": "at"}).encode() + if url == ISSUER + "/userinfo": + return 200, json.dumps(self.userinfo).encode() + return 404, b"{}" + + +class StubSampler: + def __init__(self): + self.resets = 0 + + def snapshot(self): + return {"ok": True} + + def reset_stats(self): + self.resets += 1 + + +def serve(oidc): + srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, oidc)) + 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() + out = (r.status, dict((k.lower(), v) for k, v in r.getheaders()), data, + [v for k, v in r.getheaders() if k.lower() == "set-cookie"]) + c.close() + return out + + +PUB_HOST = {"Host": "dash.example.test"} + +print("\n1. API key mode is unchanged") +srv = serve(None) +st, _, body, _ = req(srv, "GET", "/auth/config") +check("config reports key mode", st == 200 and json.loads(body)["mode"] == "key", body) +check("status without key -> 401", req(srv, "GET", "/api/status")[0] == 401) +check("status with key -> 200", req(srv, "GET", "/api/status", {"Authorization": f"Bearer {KEY}"})[0] == 200) +check("no /auth/login without OIDC", req(srv, "GET", "/auth/login")[0] == 404) +srv.shutdown() + +print("\n2. OIDC mode refuses the key and unsigned visitors") +prov = FakeProvider() +conf = {"mode": "oidc", "issuer": ISSUER, "client_id": "llm-host", "public_url": PUBLIC, + "allowed_groups": ["llm-admins"], "allowed_users": ["friend"]} +o = oidc_mod.OIDC(conf, "s3cret", http=prov) +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 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")) +st, h, _, _ = req(srv, "GET", "/auth/login", {"Host": "mybox.local:11340"}) +check("login by a LAN name starts on the public URL", st == 302 and h["location"] == PUBLIC + "/auth/login") +try: + oidc_mod.OIDC({**conf, "allowed_groups": [], "allowed_users": []}, "x") + check("an allow list is required", False) +except ValueError: + check("an allow list is required", True) + + +def login(claims_over=None, userinfo=None, cookie_state=None, tamper_state=None): + """Run /auth/login then /auth/callback. Returns (callback status, session cookie or None, body).""" + st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST) + assert st == 302, st + q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()} + code = "code-" + q["state"][:8] + prov.challenges[code] = q["code_challenge"] + prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "iat": 1, "sub": "u1", + "nonce": q["nonce"], "preferred_username": "alice", **(claims_over or {})} + prov.userinfo = {"sub": "u1", "preferred_username": "alice", "name": "Alice", + "groups": ["llm-admins"]} if userinfo is None else userinfo + state_cookie = cookies[0].split(";")[0] + if cookie_state is not None: + state_cookie = f"{oidc_mod.STATE_COOKIE}={cookie_state}" + st, h, body, cookies = req(srv, "GET", "/auth/callback?" + urllib.parse.urlencode( + {"code": code, "state": tamper_state or q["state"], "iss": ISSUER}), {**PUB_HOST, "Cookie": state_cookie}) + sess = next((c.split(";")[0] for c in cookies if c.startswith(oidc_mod.SESSION_COOKIE + "=")), None) + return st, sess, body, q, h + + +print("\n3. the authorization request") +st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST) +q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()} +check("redirects to the provider", h["location"].startswith(ISSUER + "/authorize?")) +check("PKCE S256", q.get("code_challenge_method") == "S256" and len(q.get("code_challenge", "")) == 43) +check("redirect URI is the public callback", q.get("redirect_uri") == PUBLIC + "/auth/callback") +check("asks for groups", "groups" in q.get("scope", "").split()) +check("state cookie is HttpOnly, Secure, Lax, scoped to /auth/", + all(a in cookies[0] for a in ("HttpOnly", "Secure", "SameSite=Lax", "Path=/auth/")), cookies) + +print("\n4. a good sign-in") +st, sess, body, q, h = login() +check("callback -> 302 home", st == 302 and h["location"] == "/", (st, body)) +check("session cookie set", sess is not None) +st, _, body, _ = req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess}) +check("status with session -> 200", st == 200, st) +st, _, body, _ = req(srv, "GET", "/auth/config", {**PUB_HOST, "Cookie": sess}) +check("config names the user", json.loads(body)["user"] == "alice" and json.loads(body)["name"] == "Alice", body) +st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess}) +check("POST without Origin -> 403", st == 403, st) +st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"}) +check("POST from another origin -> 403", st == 403, st) +st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC}) +check("POST from the dashboard's origin -> 200", st == 200, st) +check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions) + +print("\n5. sign-ins that must fail") +before = len(o.sessions) +st, sess2, body, *_ = login(cookie_state="someone-elses-state") +check("state cookie mismatch -> 403, no session", st == 403 and sess2 is None, st) +st, sess2, *_ = login(claims_over={"nonce": "wrong"}) +check("wrong nonce -> 403", st == 403 and sess2 is None, st) +st, sess2, *_ = login(claims_over={"aud": "other-client"}) +check("ID token for another client -> 403", st == 403 and sess2 is None, st) +st, sess2, *_ = login(claims_over={"iss": "https://evil.test"}) +check("ID token from another issuer -> 403", st == 403 and sess2 is None, st) +st, sess2, *_ = login(claims_over={"exp": 1}) +check("expired ID token -> 403", st == 403 and sess2 is None, st) +st, sess2, body, *_ = login(userinfo={"sub": "u1", "preferred_username": "stranger", "groups": ["users"]}, + claims_over={"preferred_username": "stranger"}) +check("not in an allowed group -> 403", st == 403 and sess2 is None and b"isn't allowed" in body, body[:200]) +st, sess2, *_ = login(userinfo={"sub": "u1", "preferred_username": "friend", "groups": []}, + claims_over={"preferred_username": "friend"}) +check("an allowed username gets in without the group", st == 302 and sess2 is not None, st) +st, sess3, *_ = login(userinfo={"sub": "OTHER", "preferred_username": "x", "groups": ["llm-admins"]}, + claims_over={"preferred_username": "stranger"}) +check("userinfo for a different sub is ignored", st == 403 and sess3 is None, st) +st, _, _, _ = req(srv, "GET", "/auth/callback?error=access_denied&state=x", {**PUB_HOST, "Cookie": f"{oidc_mod.STATE_COOKIE}=x"}) +check("provider error -> 403", st == 403, st) +check("no stray sessions from the failures", len(o.sessions) == before + 1, len(o.sessions)) + +# A state can be used once. +st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST) +q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()} +prov.challenges["c1"] = q["code_challenge"] +prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "sub": "u1", "nonce": q["nonce"]} +prov.userinfo = {"sub": "u1", "preferred_username": "alice", "groups": ["llm-admins"]} +cb = "/auth/callback?" + urllib.parse.urlencode({"code": "c1", "state": q["state"]}) +hdr = {**PUB_HOST, "Cookie": cookies[0].split(";")[0]} +check("first use of a state works", req(srv, "GET", cb, hdr)[0] == 302) +check("replaying it -> 403", req(srv, "GET", cb, hdr)[0] == 403) + +print("\n6. sign-out") +st, sess, *_ = login() +check("logout from another origin -> 403", req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403) +st, _, _, cookies = req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC}) +check("logout -> 200 and clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies) +check("the old cookie no longer works", req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})[0] == 401) +srv.shutdown() + +print("\n7. setup keeps the dashboard's sign-in setting") +carried = cli.carried_settings({"dashboard_auth": conf, "reasoning": {"m": "low"}}, {"m"}) +check("dashboard_auth carried", carried.get("dashboard_auth") == conf, carried) +check("reasoning still carried", carried.get("reasoning") == {"m": "low"}) +check("nothing invented when unset", "dashboard_auth" not in cli.carried_settings({}, set())) + +print("\n8. the client secret is stored privately") +paths.save_secret(paths.OIDC_SECRET_FILE, "s3cret") +check("secret file is 0600", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600) +check("reads back", paths.oidc_secret() == "s3cret") + +check.done(ROOT) diff --git a/tests/test_newt.py b/tests/test_newt.py new file mode 100644 index 0000000..b753a50 --- /dev/null +++ b/tests/test_newt.py @@ -0,0 +1,163 @@ +"""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.""" +import contextlib +import hashlib +import io +import json +import sys +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.web import oidc + +harness.guard(paths, ROOT) +check = harness.Checks() + +ISSUER = "https://auth.example.test" +NEWT_SECRET = "newt-site-secret-xyz" +OIDC_SECRET = "oidc-client-secret-xyz" + +# -- fakes ------------------------------------------------------------------------------ +calls = [] +installed = set() +service.install = lambda n: (calls.append(("install", n)), installed.add(n)) +service.uninstall = lambda n: (calls.append(("uninstall", n)), installed.discard(n)) +service.restart = lambda n: calls.append(("restart", n)) or True +service.installed = lambda n: n in installed +service.state = lambda n: ("active", 1.0) + +FAKE_BIN = b"\x7fELF fake newt" +newt.SHA256 = {k: hashlib.sha256(FAKE_BIN).hexdigest() for k in newt.SHA256} +fetches = [] +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 + + +def run(argv, env=None): + import os + 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 + try: + with contextlib.redirect_stdout(out): + cli.main(argv) + except SystemExit as e: + code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1) + if isinstance(e.code, str): + out.write(e.code) + finally: + for k, v in saved.items(): + os.environ.pop(k, None) + if v is not None: + os.environ[k] = v + return code, out.getvalue() + + +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} + +print("\n1. a plain install doesn't include newt") +check("setup's services are model and web only", service.NAMES == ("model", "web"), service.NAMES) +check("newt is an optional service", "newt" in service.OPTIONAL) + +print("\n2. the pinned download is checked") +real = dict(newt.SHA256) +newt.SHA256 = {k: "0" * 64 for k in real} +try: + newt.ensure_binary(lambda *_: None) + check("a bad checksum is refused", False) +except SystemExit as e: + check("a bad checksum is refused", "checksum" in str(e), e) +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") +calls.clear() +code, out = run(ARGS, SECRETS) +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("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") +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) + +print("\n6. 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") +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") +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("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models")) +code, out = run(["remove-newt"]) +check("running it again is harmless", code == 0 and "wasn't installed" in out, out) + +check.done(ROOT) From 6fd82448c5a5c0e215770c02a70c50c688e8cf2c Mon Sep 17 00:00:00 2001 From: neil Date: Thu, 5 Nov 2026 22:51:21 -0800 Subject: [PATCH 06/10] Dashboard: an API key button that shows the key with a copy button Behind the same sign-in as the rest of the dashboard (GET /api/key, no-store), so whoever can open the dashboard can hand the key to a client without a shell on the server. Co-Authored-By: Claude Opus 5.5 --- README.md | 3 ++- llmhost/web/index.html | 45 ++++++++++++++++++++++++++++++++++-- llmhost/web/server.py | 5 ++++ tests/test_dashboard_auth.py | 8 +++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8f5bc98..a064f65 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,8 @@ It ends by printing the two Pangolin HTTP resources to create, both pointing at | dashboard, at the `--public-url` host | `:` | llm-host, through your OIDC provider | | API, at a host of your choice | `:` | llm-host, with the API key | -Clients then use `https:///v1` with the key from `llmhost key`. +Clients then use `https:///v1` with the key from `llmhost key`, or from the dashboard's **API key** button, +which shows it to anyone signed in, with a copy button. For Authelia, the client looks like this: diff --git a/llmhost/web/index.html b/llmhost/web/index.html index bb3f75e..08eff7e 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -158,6 +158,9 @@ pre { background: var(--panel-2); color: var(--text); margin-bottom: 12px; } .dialog .err { color: var(--bad); font-size: 12.5px; min-height: 18px; margin: -6px 0 8px; } +.dialog .keyrow { display: flex; gap: 6px; margin-bottom: 14px; } +.dialog .keyrow input { margin: 0; flex: 1; min-width: 0; } +.dialog .actions { display: flex; justify-content: flex-end; } .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; } @@ -171,6 +174,7 @@ pre { + @@ -276,6 +280,14 @@ pre { Sign in +
+ +
diff --git a/llmhost/web/oidc.py b/llmhost/web/oidc.py index e2ac810..ceda0a9 100644 --- a/llmhost/web/oidc.py +++ b/llmhost/web/oidc.py @@ -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) diff --git a/llmhost/web/server.py b/llmhost/web/server.py index a327ffd..8b65794 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -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() diff --git a/llmhost/web/sessions.py b/llmhost/web/sessions.py new file mode 100644 index 0000000..372f05b --- /dev/null +++ b/llmhost/web/sessions.py @@ -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) diff --git a/opencode-install.sh b/opencode-install.sh new file mode 100755 index 0000000..a58fa87 --- /dev/null +++ b/opencode-install.sh @@ -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-.key (mode 600) +# 4. adds an llmhost- 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/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 </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 <"$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." diff --git a/tests/fixtures/qr_golden.json b/tests/fixtures/qr_golden.json new file mode 100644 index 0000000..cff048c --- /dev/null +++ b/tests/fixtures/qr_golden.json @@ -0,0 +1 @@ +{"hello world": {"version": 1, "mask": 2, "rows": ["111111100101101111111", "100000100010001000001", "101110101111001011101", "101110101110101011101", "101110101010101011101", "100000101001001000001", "111111101010101111111", "000000001010000000000", "101111100101001111100", "011011010101111111101", "101011110110111001110", "101001000101110011100", "000101111100111000001", "000000001010100011001", "111111100001001000110", "100000101000010101111", "101110101001001100001", "101110101100111111000", "101110101100100100100", "100000100110110011100", "111111101101101010010"]}, "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz": {"version": 6, "mask": 2, "rows": ["11111110011100001001101101101101101111111", "10000010000000101010000011010110001000001", "10111010101001001001010110000011001011101", "10111010110100010011101101101101101011101", "10111010110100101101101101101101101011101", "10000010111001101110000011010110001000001", "11111110101010101010101010101010101111111", "00000000111000001011010110000011000000000", "10111110011101110101101101101101101111100", "11110101011000001101101101101101101110101", "00101111100011101110000011010110011000100", "01100001111111010011010110000011011001011", "10000010100010000101001101101101100101111", "10111001011000101100101101101101101110101", "10101011100011101111000011010110011000100", "10101001111111001011110110000011011001011", "11010010000000011101101101101101100101111", "10010100111010110101101101101101101110101", "01100111011100000100000011010110011000100", "11101000101000001111010110000011011001011", "11010010011000101001110101101101100101111", "10110000110010110111100101101101101110101", "01100110111101100110000011010110011000100", "11011000111001101011010110000011011001010", "11110011110011000101101101101101100101100", "00100001110000101101101101101101101110101", "11001110110110101110000011010110011000100", "00110001001101101011010110000011011001011", "00010110111011011101101101101101100101111", "10101101110110011100001101101101101110101", "10001010110010101110100011010110011000100", "10110001001011111010010110000011011001011", "10001110111011011100101101101101111111111", "00000000100000000001101101101101100010101", "11111110010110111010001011010111101010100", "10000010111111100001000110000011100011011", "10111010110010001011111101101100111111111", "10111010100000100101100101101100100100111", "10111010111111111010000011010110101110100", "10000010001111100111010110000011111001010", "11111110100011000011101101101101011001100"]}, "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy": {"version": 10, "mask": 1, "rows": ["111111101000001100111000101010101010101010101111001111111", "100000100000111110001011011011101110111011101101001000001", "101110101110100001010011010001000100010001000111001011101", "101110100111001101001101110101010101010101010101001011101", "101110100101101100100000111111101010101010101001001011101", "100000101000111110000011011000101110111011101110001000001", "111111101010101010101010101010101010101010101010101111111", "000000000001100111010100111000111011101110111010100000000", "101000110001111010110010001111101010101010101010000100101", "000010000010010000011111001101010101010101010101010100111", "000111100111110111111100101100010001000100010000100100101", "000110000001110001010100110110111011101110111010101111010", "011100101001101010110110000010101010101010101010001010010", "111101000010001110011001001101010101010101010101010100111", "001000100111100001111010101100010001000100010000100100101", "000101000011100101010100110110111011101110111010101111010", "011101101001101000101010000010101010101010101010001010001", "110111000110000010001101001101010101010101010101010100111", "000011100001100011001100101100010001000100010000100100101", "001011010101100010000010110110111011101110111010101111010", "011111110001001000010110000010101010101010101010001010010", "110101000110100010110011001101010101010101010101010100111", "000000110101000010111100101100010001000100010000100100101", "001011000110100011001010110110111011101110111010101111010", "011111111100101001001110000010101010101010101010001010010", "110101010010000011010011001101010101010101010101010100111", "100011111100110010000100111111110001000100010000111110101", "011010001111100011110010111000111011101110111010100011010", "101110101100001001001110011010101010101010101011101010010", "000110001010001010010011011000110101010101010101100010111", "111111111101110100000000101111110001000100010000111110101", "101011000111011001110100111011111011101110111011111011010", "110000100100001111001010011001001010101010101011010000010", "010000010010011000010111001101010101010101010100010100110", "111010101111111000000010100010110001000100010000001010100", "100011001101000111110010111011111011101110111011111011000", "110011100000000011010010011001001010101010101011010000011", "010000010010000100011011001101010101010101010100010100111", "110000101111111000110010100010110001000100010000001010101", "100000001111000010000100111011111011101110111011111011010", "110010100000000011010010011001001010101010101011010000010", "010010010010000101101011001101010101010101010100010100111", "110010101001011001001010100010110001000100010000001010101", "110011001111000011011100111011111011101110111011111011010", "100011110101100011011010011001001010101010101011010000010", "010011011100000101101011001101010101010101010100010100111", "101001110001110000001010100010110001000100010000001010101", "111110001111100011100100111011111011101110111011111011010", "000000101101001111111010011111101010101010101011111110010", "000000001100111001001011001000110101010101010101100010111", "111111101001100100001010101010110001000100010001101010101", "100000100110100111100000101000111011101110111010100011010", "101110100101001001111010001111101010101010101010111110010", "101110100100100101001111011110110101010101010101101110100", "101110101111110110001000110010110001000100010000101010111", "100000100110100001100000110101011011101110111011010101000", "111111101111010011101110001100001010101010101011000100001"]}} \ No newline at end of file diff --git a/tests/harness.py b/tests/harness.py index 5d044e9..8bbad84 100644 --- a/tests/harness.py +++ b/tests/harness.py @@ -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}") diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.py index b020340..7c543b0 100644 --- a/tests/test_dashboard_auth.py +++ b/tests/test_dashboard_auth.py @@ -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")) diff --git a/tests/test_newt.py b/tests/test_newt.py index b753a50..a4c0e1b 100644 --- a/tests/test_newt.py +++ b/tests/test_newt.py @@ -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) diff --git a/tests/test_opencode_install.py b/tests/test_opencode_install.py new file mode 100644 index 0000000..2677103 --- /dev/null +++ b/tests/test_opencode_install.py @@ -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) diff --git a/tests/test_otp.py b/tests/test_otp.py new file mode 100644 index 0000000..1dc6373 --- /dev/null +++ b/tests/test_otp.py @@ -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) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 5cbd7a7..2ea7703 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -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 From 3e9ebeed42a2c450eb3f2c417fc47c37815415e4 Mon Sep 17 00:00:00 2001 From: neil Date: Fri, 6 Nov 2026 18:35:41 -0800 Subject: [PATCH 10/10] Hand out the right opencode command: the API's public URL, and setup uses the install script install-newt now asks for the API's public URL first (--api-url) and records it; it names the Pangolin resource and refuses an endpoint on the same host. expose-dashboard records only that the dashboard is public. One rule (opencode.client_targets) decides which opencode-install.sh commands are shown -- local only without a tunnel; internet and local with one; internet only once the dashboard is public -- and setup's closing message, `llmhost opencode-config` and the dashboard's Connect dialog all use it. Setup's offer to install opencode now goes through opencode-install.sh --install-only, a new mode that only installs opencode; this machine's own provider is still configured by llm-host, which keeps it in sync on every switch. Co-Authored-By: Claude Opus 5.5 --- README.md | 32 +++++++++++---- llmhost/cli.py | 63 +++++++++++++++++++++-------- llmhost/opencode.py | 72 +++++++++++++++++++++++++++++++--- llmhost/web/index.html | 45 +++++++++++---------- llmhost/web/server.py | 56 ++++++-------------------- opencode-install.sh | 31 +++++++++++---- tests/test_dashboard_auth.py | 16 +++++++- tests/test_newt.py | 37 +++++++++++++++-- tests/test_opencode.py | 6 +++ tests/test_opencode_install.py | 17 +++++++- 10 files changed, 266 insertions(+), 109 deletions(-) diff --git a/README.md b/README.md index d1aa067..91948d1 100644 --- a/README.md +++ b/README.md @@ -93,14 +93,19 @@ a third user service, in userspace (no root). It's a pinned release, checked aga 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 +llmhost install-newt --api-url https://llm-api.example.com \ + --endpoint https://pangolin.example.com --newt-id ``` +`--api-url` is where clients will reach the API: a domain you'll add as a resource on Pangolin, not Pangolin's own +address (`--endpoint`). It's asked for first, because llm-host uses it to describe the resource and to print the +right `opencode-install.sh` command everywhere it gives one. + 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 → `:`, +Then add one HTTP resource in Pangolin, for the API: the `--api-url` host → `:`, 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:///v1` with the key; for opencode, see [`opencode-install.sh`](#connecting-opencode). @@ -171,15 +176,27 @@ page. While OIDC is on, it's the only way in, and codes come back with `remove-o - **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 → `:`) and, once you -press Enter, checks the public URL reaches this dashboard. +press Enter, checks the public URL reaches this dashboard. It records only that the dashboard is public, not where. + +### Which address clients are given + +Setup's closing message, `llmhost opencode-config` and the dashboard's **Connect** dialog all print the +`opencode-install.sh` command, for these addresses: + +| state | commands shown | +|---|---| +| no tunnel | the local network (`http://.local:`) | +| `install-newt` done, dashboard local | the internet (`--api-url`), then the local network | +| `expose-dashboard` done | the internet only, since the dashboard is then seen from outside | `llmhost status` shows the tunnel and sign-in settings. `setup` and `update` keep them, and `update` moves newt to a newly pinned release. Each step has an undo: `remove-newt`, `remove-oidc`, `remove-otp`. ## Connecting opencode -**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official -installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` +**On the server itself**, setup handles it: if opencode isn't installed it offers to install it, through +`opencode-install.sh --install-only` like any other machine (which runs opencode's official installer, into +`~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` pointing at `http://localhost:/v1` and reading the key straight from llm-host's key file. It shows up in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`. @@ -187,8 +204,9 @@ the file up as `opencode.json.before-llmhost`. (`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`. A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead. -**On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner -that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (mybox.local)` +**On another machine**, use `opencode-install.sh` (below); setup ends by printing the exact command for this +server. To do it by hand instead, run `llmhost opencode-config` on the server. It prints a provider block and a +one-liner that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (mybox.local)` — under the provider id `llmhost-`. **On any machine, in one step**, run `opencode-install.sh` from this repo. It needs only the API's address and diff --git a/llmhost/cli.py b/llmhost/cli.py index 7a2e0dd..3fc483e 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -119,7 +119,7 @@ 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", "dashboard_key_login"): # set by install-*/expose-dashboard, not the plan + for k in ("newt", "dashboard_auth", "dashboard_key_login", "dashboard_public"): # set by install-*/expose-dashboard if old.get(k) is not None: # dashboard_key_login is False when it matters out[k] = old[k] return out @@ -208,7 +208,11 @@ Done. Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch progress with: llmhost watch"}""") if not a.no_opencode: setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode) - say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.") + say("\nOther machines: connect their opencode to this server with one line there. It installs\n" + "opencode if needed, asks for the API key (show it here with `llmhost key`), and adds the\n" + "server to opencode.json.") + for where, url in opencode.client_targets(cfg, host): + say(f" {where}:\n {opencode.remote_command(url)}") if os.environ.get("LLMHOST_PATH_NOTE"): say("\n" + os.environ["LLMHOST_PATH_NOTE"]) @@ -358,7 +362,9 @@ def cmd_status(a): + (["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']}") + api = cfg["newt"].get("api_url") + say(f"tunnel newt -> {cfg['newt']['endpoint']}" + (f"; API at {api}/v1" if api else "")) + say(f"dashboard {'public (expose-dashboard)' if cfg.get('dashboard_public') else 'local network only'}") def cmd_models(a): @@ -546,8 +552,16 @@ def cmd_install_newt(a): 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")) + api_url = _ask("The API's public URL, as clients will reach it (e.g. https://llm-api.example.com)", + a.api_url, old_n.get("api_url"), "--api-url").strip().rstrip("/") + api_url = _check_url("API URL", api_url[:-3] if api_url.endswith("/v1") else api_url) + + say("\nPangolin site (Pangolin: Sites -> Add Site -> Newt):") + endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint (your Pangolin server, not the API's URL)", + a.endpoint, old_n.get("endpoint"), "--endpoint")) + if urllib.parse.urlsplit(endpoint).netloc == urllib.parse.urlsplit(api_url).netloc: + sys.exit("The Pangolin endpoint is the Pangolin server itself; the API's URL is a resource on it, " + "so the two can't be the same.") site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id") 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") @@ -555,7 +569,7 @@ def cmd_install_newt(a): newt.ensure_binary(say) if newt_secret != "keep": paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret) - cfg["newt"] = {"endpoint": endpoint, "id": site_id} + cfg["newt"] = {"endpoint": endpoint, "id": site_id, "api_url": api_url} paths.save_config(cfg) service.install("newt") if not service.restart("newt"): @@ -563,12 +577,13 @@ def cmd_install_newt(a): ip = lan_ip() say(f""" Done. newt is running. In Pangolin, add an HTTP resource on this site for the API: - -> http://{ip}:{cfg['api_port']} + {urllib.parse.urlsplit(api_url).netloc} -> 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:///v1 with the API key; for opencode, see the dashboard's -Connect button, or opencode-install.sh in the llm-host repo. +Clients then use {api_url}/v1 with the API key. To connect opencode on another machine, run +this there (it asks for the key, which `llmhost key` shows): + {opencode.remote_command(api_url)} 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 @@ -583,6 +598,7 @@ def cmd_remove_newt(a): shutil.rmtree(paths.NEWT_DIR, ignore_errors=True) paths.NEWT_SECRET_FILE.unlink(missing_ok=True) had = bool(cfg.pop("newt", None)) + cfg.pop("dashboard_public", None) # nothing is public without the tunnel paths.save_config(cfg) say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.") @@ -760,6 +776,10 @@ In Pangolin, on the same site as the API, add an HTTP resource: authentication {pangolin_auth}""") if oidc_on: say(f" and make sure your OIDC client allows the redirect URI {public_url}/auth/callback") + # Only that it's public, not where: what's handed to clients is the API's address, and + # a public dashboard is seen from outside, so it stops offering the LAN one. + cfg["dashboard_public"] = True + paths.save_config(cfg) if not sys.stdin.isatty(): return input("\nPress Enter once the resource is saved, to check it from here... ") @@ -788,24 +808,32 @@ def cmd_download(a): def cmd_opencode(a): cfg = _service_check() - host = a.host or default_host() + if a.host: # an address given explicitly: that one, as before + targets = [("", f"http://{a.host}:{cfg['api_port']}")] + else: + targets = opencode.client_targets(cfg, default_host()) + base = targets[0][1] + host = urllib.parse.urlsplit(base).hostname prov = a.provider or opencode.remote_provider(host) keyfile = opencode.remote_key_file(prov) snippet = { "$schema": "https://opencode.ai/config.json", - "provider": {prov: opencode.provider_block(cfg, host, keyfile, host)}, + "provider": {prov: opencode.provider_block(cfg, host, keyfile, host, base_url=base + "/v1")}, "model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry } if a.json: say(json.dumps(snippet, indent=2)) return - say(f"""(On this machine itself, `llmhost opencode-setup` does all of this automatically.) + say("(On this machine itself, `llmhost opencode-setup` does all of this automatically.)\n\n" + "On another machine, run this there. It installs opencode if needed, asks for the API key\n" + "(`llmhost key` shows it here), and adds this server to opencode.json:") + for where, url in targets: + say(f" {where}:\n {opencode.remote_command(url)}" if where else f" {opencode.remote_command(url)}") + say(f""" +Or by hand, for {base}/v1: -On another machine running opencode: - -1. Save the API key: - mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} - (or paste the output of `llmhost key` into {keyfile}) +1. Save the API key: paste the output of `llmhost key` into {keyfile} (mode 600), or + mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{default_host()} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} 2. Merge this into ~/.config/opencode/opencode.json: """) @@ -1001,6 +1029,7 @@ def main(argv=None): sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key) 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("--api-url", help="the API's public address, e.g. https://llm-api.example.com (a resource on Pangolin)") s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)") s.set_defaults(fn=cmd_install_newt) sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt) diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 090bb7a..1c2855a 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -17,6 +17,7 @@ never overwritten. Other providers and settings are left untouched. """ import json import os +import re import shutil import subprocess from pathlib import Path @@ -28,7 +29,8 @@ PROVIDER = "llmhost" DISPLAY = "LLMHost" LOCAL_LABEL = "Local" LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]") -INSTALL_URL = "https://opencode.ai/install" +INSTALL_SCRIPT = paths.SRC / "opencode-install.sh" +DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too def find(): @@ -40,12 +42,70 @@ def find(): def install(log=print): - """Run opencode's official installer (installs to ~/.opencode/bin, adds it to PATH).""" - log(f"$ curl -fsSL {INSTALL_URL} | bash") - r = subprocess.run(["bash", "-c", f"set -o pipefail; curl -fsSL {INSTALL_URL} | bash"]) + """Install opencode the way every machine does: through llm-host's opencode-install.sh, + which runs opencode's official installer (into ~/.opencode/bin, added to PATH). Only + the install step: this machine's provider is configure()'s, since it reads the key + file in place and is kept in sync on every switch.""" + log(f"$ {INSTALL_SCRIPT.name} --install-only") + r = subprocess.run(["bash", str(INSTALL_SCRIPT), "--install-only"]) return find() if r.returncode == 0 else None +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(): + """opencode-install.sh's URL in the repo this server was installed from, so the command + handed to other machines follows a fork and needs nothing but the API to work. Falls + back to the main repo.""" + global _installer + if _installer is None: + 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", INSTALL_SCRIPT.name) + or raw_file_url(DEFAULT_REPO, "main", INSTALL_SCRIPT.name)) + return _installer + + +def remote_command(base_url): + """The one line another machine runs to connect its opencode to this server.""" + return f'/bin/bash -c "$(curl -fsSL {installer_url()})" -- --url {base_url}' + + +def client_targets(cfg, lan_host): + """Where other machines reach the API, as [(where, base URL)], most useful first. + + The API's public address (recorded by `llmhost install-newt`) when there is one, and + the local-network address too unless the dashboard is public -- a public dashboard + is seen from outside, where a LAN address is only noise.""" + lan = ("on your local network", f"http://{lan_host}:{cfg['api_port']}") + public = (cfg.get("newt") or {}).get("api_url") + if not public: + return [lan] + out = [("from the internet", public)] + if not cfg.get("dashboard_public"): + out.append(lan) + return out + + def config_dir(): return Path(os.environ.get("XDG_CONFIG_HOME") or paths.HOME / ".config") / "opencode" @@ -139,7 +199,7 @@ def effort_variants(): return {level: {"disabled": True} for level in OPENCODE_EFFORTS} -def provider_block(cfg, host, key_path, label, mark_loaded=False): +def provider_block(cfg, host, key_path, label, mark_loaded=False, base_url=None): # A single entry, keyed by the alias the API also answers to. Listing every model that # fits would be a menu of four things that 404 and one that works, and naming the loaded # one would break every client's saved default on each `llmhost switch`. @@ -157,7 +217,7 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False): return { "npm": "@ai-sdk/openai-compatible", "name": f"{DISPLAY} ({label})", - "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, + "options": {"baseURL": base_url or f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, "models": models, } diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 6ba2d48..dfea050 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -173,7 +173,9 @@ pre { .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; } +.dialog .snip pre.cmd { white-space: pre-wrap; overflow-wrap: anywhere; } +#cx-installs .where { font-size: 12.5px; color: var(--muted); margin: 0 0 4px; } +#cx-installs .snip { margin: 0 0 14px; } .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; } @@ -308,15 +310,12 @@ pre {

Add to opencode

-

The API's address, as the machine running opencode reaches it:

-
-

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 - opencode.json, keeping their other settings:

-
+

Run this on the machine with opencode, 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 opencode.json, keeping their other settings.

+
- Or set it up by hand + Or set it up by hand
  1. Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
  2. @@ -427,7 +426,22 @@ function closeConnect() { // filled in here: baseURL, and the provider id and label named after its host. function renderOpencode() { if (!CONNECT) return; - let url = $("cx-url").value.trim().replace(/\/+$/, ""); + // One command per address the API is reached at (server's choice; see client_targets). + const box = $("cx-installs"); box.textContent = ""; + for (const t of CONNECT.targets) { + if (CONNECT.targets.length > 1) { + const w = document.createElement("div"); w.className = "where"; + w.textContent = t.where[0].toUpperCase() + t.where.slice(1) + ":"; box.appendChild(w); + } + const snip = document.createElement("div"); snip.className = "snip"; + const pre = document.createElement("pre"); pre.className = "cmd"; pre.textContent = t.command; + const b = document.createElement("button"); b.className = "small"; b.textContent = "Copy"; + b.onclick = async () => toast(await copyText(t.command) ? "Copied" : "Couldn't copy; select it and copy by hand"); + snip.append(pre, b); box.appendChild(snip); + } + // By hand: for the first (most useful) address. + let url = CONNECT.targets[0].url.replace(/\/+$/, ""); + $("cx-manual-title").textContent = `Or set it up by hand (for ${url})`; let host = ""; try { host = new URL(url).hostname; } catch (e) {} if (url && !/\/v1$/.test(url)) url += "/v1"; @@ -450,27 +464,16 @@ 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) {} } $("connect").onclick = async () => { let c; try { c = await api("/api/connect"); } catch (e) { if (e.message !== "unauthorized") toast("Couldn't load: " + e.message); return; } CONNECT = c; $("cx-key").value = c.key; - // The public API address can't be known here, so remember what the viewer typed; on a - // plain-http LAN visit the API is on this same host, at its own port. - let saved = ""; - try { saved = localStorage.getItem("llmhost-api-url") || ""; } catch (e) {} - if (!saved && location.protocol === "http:") saved = `http://${location.hostname}:${c.api_port}/v1`; - $("cx-url").value = saved; renderOpencode(); $("connect-modal").classList.add("show"); $("cx-close").focus(); }; -$("cx-url").addEventListener("input", renderOpencode); document.querySelectorAll("#connect-modal [data-copy]").forEach((b) => { b.onclick = async () => toast(await copyText($(b.dataset.copy).textContent) ? "Copied" : "Couldn't copy; select it and copy by hand"); }); diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 8b65794..9deac44 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -417,42 +417,8 @@ class Sampler: threading.Thread(target=fn, args=("model",), daemon=True).start() -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 +# The opencode installer's URL is worked out once, from the repo this was installed from. +raw_file_url, installer_url = opencode.raw_file_url, opencode.installer_url def make_handler(sampler, key, oidc=None, otp=None, key_login=True): @@ -602,17 +568,19 @@ def make_handler(sampler, key, oidc=None, otp=None, key_login=True): if self.authed(): self.send_json(200, sampler.snapshot()) elif path == "/api/connect": - # What the Connect dialog hands to clients: the key, and opencode's provider - # block from the same builder as `llmhost opencode-config`. The public API - # address can't be known here, so the page fills in baseURL, the provider id - # and its label from what the viewer types. Behind the same sign-in as - # everything else; send_json marks it no-store. + # What the Connect dialog hands to clients: the key; the API's addresses with + # the opencode-install.sh command for each, chosen by the same rule as setup and + # `llmhost opencode-config` (opencode.client_targets); and opencode's provider + # block for setting it up by hand, whose address-dependent parts the page fills + # in. Behind the same sign-in as everything else; send_json marks it no-store. if self.authed(): cfg = paths.load_config() or sampler.cfg + h = socket.gethostname() + targets = [{"where": w, "url": u, "command": opencode.remote_command(u)} + for w, u in opencode.client_targets(cfg, h if "." in h else h + ".local")] 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, - "installer": installer_url()}) + self.send_json(200, {"key": key, "model": plan.SERVED_ALIAS, "opencode": block, + "targets": targets}) elif path == "/api/logs": if self.authed(): lines = [l for l in service.logs("model", 1500) diff --git a/opencode-install.sh b/opencode-install.sh index a58fa87..d162cf2 100755 --- a/opencode-install.sh +++ b/opencode-install.sh @@ -24,6 +24,7 @@ # --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 +# --install-only only install opencode (no --url or key needed); `llmhost setup` uses this # --remove take this server back out of opencode's config # Written for bash 3.2 so it runs on stock macOS. set -euo pipefail @@ -44,12 +45,13 @@ Connect opencode to an llm-host server, installing opencode first if needed. --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 + --install-only only install opencode (no --url or key needed) --remove take this server back out of opencode's config EOF } [ "${1:-}" = "--" ] && shift -URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0 +URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0; INSTALL_ONLY=0 while [ $# -gt 0 ]; do case "$1" in --url) URL="${2:-}"; shift 2 ;; @@ -59,12 +61,30 @@ while [ $# -gt 0 ]; do --default) DEFAULT="yes"; shift ;; --no-default) DEFAULT="no"; shift ;; --skip-install) INSTALL=0; shift ;; + --install-only) INSTALL_ONLY=1; shift ;; --remove) REMOVE=1; shift ;; -h|--help) usage; exit 0 ;; *) die "unknown option: $1 (see --help)" ;; esac done +find_opencode() { + OC="$(command -v opencode || true)" + if [ -z "$OC" ] && [ -x "$HOME/.opencode/bin/opencode" ]; then OC="$HOME/.opencode/bin/opencode"; fi +} +install_opencode() { + say "Installing opencode (official installer)" + curl -fsSL https://opencode.ai/install | bash + find_opencode + [ -n "$OC" ] || die "opencode didn't install; see the output above" +} + +if [ "$INSTALL_ONLY" = 1 ]; then + find_opencode + if [ -n "$OC" ]; then say "opencode is already installed ($OC)"; else install_opencode; fi + exit 0 +fi + # A terminal to ask on, even when this script arrived on stdin. TTY="" if [ -r /dev/tty ] && [ -w /dev/tty ] && (: /dev/null; then TTY=/dev/tty; fi @@ -168,15 +188,10 @@ fi say "Server OK" # ---- opencode ------------------------------------------------------------------------ -OC="$(command -v opencode || true)" -[ -n "$OC" ] || { [ -x "$HOME/.opencode/bin/opencode" ] && OC="$HOME/.opencode/bin/opencode"; } || true +find_opencode 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" + install_opencode else warn "opencode isn't installed; configuring it anyway (--skip-install)" fi diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.py index 7c543b0..3ce7e19 100644 --- a/tests/test_dashboard_auth.py +++ b/tests/test_dashboard_auth.py @@ -109,8 +109,20 @@ 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"]) +check("one address before any tunnel: the LAN", len(cx["targets"]) == 1 + and cx["targets"][0]["url"].endswith(f":{harness.config()['api_port']}"), cx["targets"]) +check("with its opencode-install.sh command", "/opencode-install.sh)\" -- --url http://" in cx["targets"][0]["command"], + cx["targets"]) +c2 = harness.config(); c2["newt"] = {"endpoint": "https://p.example.test", "id": "x", "api_url": "https://llm-api.example.test"} +paths.save_config(c2) +cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2]) +check("tunnel, local dashboard: internet then LAN", [t["where"] for t in cx["targets"]] + == ["from the internet", "on your local network"] and cx["targets"][0]["url"] == "https://llm-api.example.test", cx["targets"]) +c2["dashboard_public"] = True +paths.save_config(c2) +cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2]) +check("public dashboard: the internet only", [t["url"] for t in cx["targets"]] == ["https://llm-api.example.test"], cx["targets"]) +paths.save_config(harness.config()) 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") diff --git a/tests/test_newt.py b/tests/test_newt.py index a4c0e1b..d2e1fa7 100644 --- a/tests/test_newt.py +++ b/tests/test_newt.py @@ -77,7 +77,9 @@ cfg = harness.config() paths.save_config(cfg) paths.api_key(create=True) -NEWT_ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123"] +NEWT_ARGS = ["install-newt", "--api-url", "https://llm-api.example.test", "--endpoint", "https://pangolin.example.test", + "--newt-id", "site123"] +NEWT_CONF = {"endpoint": "https://pangolin.example.test", "id": "site123", "api_url": "https://llm-api.example.test"} OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER, "--client-id", "client-from-provider", "--allow-group", "llm-admins"] @@ -102,13 +104,25 @@ 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: the API only") +print("\n3a. the client commands before the tunnel: the local network only") +code, out = run(["opencode-config"]) +check("opencode-config: one command, the LAN address", code == 0 and out.count("opencode-install.sh") == 1 + and f"--url http://{cli.default_host()}:{cfg['api_port']}" in out, out) +code, out = run(["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "x"], + {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) +check("the API's public URL is required", code != 0 and "--api-url" in out, out) +code, out = run(["install-newt", "--api-url", "https://pangolin.example.test", "--endpoint", "https://pangolin.example.test", + "--newt-id", "x"], {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) +check("API URL = Pangolin endpoint is refused", code != 0 and "can't be the same" in out, out) 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(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("newt config saved, with the API's public URL", c.get("newt") == NEWT_CONF, c.get("newt")) +check("the resource is named by the API's host", f"llm-api.example.test -> http://" in out, out) +check("prints the opencode command for the public URL", "opencode-install.sh)\" -- --url https://llm-api.example.test" in out, out) 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 not restarted", ("restart", "web") not in calls, calls) @@ -119,8 +133,18 @@ check("secret saved 0600, not in config or output", 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 keeps what it isn't given", code == 0 and c["newt"] == {"endpoint": "https://pangolin.example.test", "id": "site456"} +check("re-run keeps what it isn't given", code == 0 and c["newt"] == {**NEWT_CONF, "id": "site456"} and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out) +code, out = run(["install-newt", "--api-url", "https://llm-api.example.test/v1/"]) +check("a trailing /v1 is dropped", code == 0 and paths.load_config()["newt"]["api_url"] == "https://llm-api.example.test", out) + +print("\n3b. tunnel up, dashboard local: both commands") +code, out = run(["opencode-config"]) +check("opencode-config: internet first, then local", code == 0 and out.count("opencode-install.sh") == 2 + and out.index("--url https://llm-api.example.test") < out.index(f"--url http://{cli.default_host()}"), out) +check("by hand: for the public URL", '"baseURL": "https://llm-api.example.test/v1"' in out, out) +code, out = run(["status"]) +check("status: API URL and a local dashboard", "API at https://llm-api.example.test/v1" in out and "local network only" in out, out) print("\n4. newt starts with its credentials in the environment, not its arguments") seen = {} @@ -141,6 +165,12 @@ 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) +c = paths.load_config() +check("records that the dashboard is public, not where", c.get("dashboard_public") is True + and "dash.example.test" not in json.dumps({k: v for k, v in c.items() if k != "dashboard_auth"}), c.get("dashboard_public")) +code, out = run(["opencode-config"]) +check("dashboard public: only the internet command", code == 0 and out.count("opencode-install.sh") == 1 + and "--url https://llm-api.example.test" in out and f"http://{cli.default_host()}" not in out.split("Or by hand")[0], out) print("\n6. install-oidc") code, out = run(OIDC_ARGS) @@ -209,6 +239,7 @@ code, out = run(["remove-newt"]) c = paths.load_config() 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("and the dashboard no longer counts as public", "dashboard_public" not in c) 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) diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 048a0db..e25415b 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -327,4 +327,10 @@ check("a non-reasoning model gets no variants", "variants" not in nr["models"][" check("one entry only, named for the alias, so the client can't pick a model either", list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"])) +print("\nthe command handed to other machines") +cmd = opencode.remote_command("http://mybox.local:1134") +check("fetches opencode-install.sh from a repo and passes the URL", + cmd.startswith('/bin/bash -c "$(curl -fsSL https://') and '/opencode-install.sh)" -- --url http://mybox.local:1134' in cmd, cmd) +check("the script it names is in this repo", (harness.REPO / "opencode-install.sh").exists()) + check.done(ROOT) diff --git a/tests/test_opencode_install.py b/tests/test_opencode_install.py index 2677103..30c1c24 100644 --- a/tests/test_opencode_install.py +++ b/tests/test_opencode_install.py @@ -172,7 +172,22 @@ 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`") +print("\n5. --install-only, which `llmhost setup` uses") +home, b, oc = sandbox(with_opencode=False) +code, out = run(home, b, oc, "--install-only", key=None) +check("installs without a URL or key", code == 0 and (home / ".opencode/bin/opencode").exists(), out) +check("touches no config", not (home / ".config/opencode").exists()) +code, out = run(home, b, oc, "--install-only", key=None) +check("a second run finds it", code == 0 and "already installed" in out, out) +home, b, oc = sandbox(with_opencode=False) +env = {"HOME": str(home), "PATH": f"{b}:/usr/bin:/bin", "FAKE_OPENCODE": str(oc), + "LLMHOST_HOME": str(home / "lh"), "LLMHOST_CONFIG": str(home / "lhc"), "PYTHONPATH": str(harness.REPO)} +r = subprocess.run([sys.executable, "-c", "from llmhost import opencode; print('FOUND', opencode.install(lambda *_: None))"], + env=env, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, start_new_session=True) +check("llm-host's own opencode install goes through the script", + r.returncode == 0 and f"FOUND {home}/.opencode/bin/opencode" in r.stdout, r.stdout + r.stderr) + +print("\n6. --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)
FinishedDurationTTFTPrompt tokPrompt tok/sGenerated tokGen tok/sPeak KVPrompt tokPrompt secPrompt tok/sGenerated tokGenerated secGen tok/sPeak KV