From 04ff14c58f8928ad33962d5ae5948b9c267419f3 Mon Sep 17 00:00:00 2001 From: neil Date: Thu, 5 Nov 2026 23:03:56 -0800 Subject: [PATCH] Dashboard: Connect dialog with the API key and opencode setup The API key button is Connect again. Besides the key, it walks through adding this server to opencode: type the API's address (remembered in the browser; prefilled on a LAN visit) and it fills in a command that saves the key to a 0600 file without it touching shell history, and the provider block from the same builder as `llmhost opencode-config`. GET /api/connect replaces /api/key, behind the same sign-in. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +-- llmhost/web/index.html | 69 +++++++++++++++++++++++++++++++++--- llmhost/web/server.py | 14 +++++--- tests/test_dashboard_auth.py | 23 +++++++----- 4 files changed, 93 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index a064f65..f614274 100644 --- a/README.md +++ b/README.md @@ -112,8 +112,9 @@ 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`, or from the dashboard's **API key** button, -which shows it to anyone signed in, with a copy button. +Clients then use `https:///v1` with the key from `llmhost key`, or from the dashboard's **Connect** button. +It shows anyone signed in the key, plus the steps to add this server to opencode: type the API's address and it +fills in a key-saving command and the provider block, both with copy buttons. For Authelia, the client looks like this: diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 08eff7e..0f235aa 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -158,8 +158,18 @@ 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.wide { max-width: 620px; max-height: calc(100vh - 32px); overflow-y: auto; } +.dialog h4 { margin: 18px 0 6px; font-size: 13.5px; } +.dialog ol { margin: 0 0 12px; padding-left: 20px; color: var(--muted); font-size: 13px; } +.dialog ol li { margin-bottom: 10px; } +.dialog ol li > div { color: var(--text); } .dialog .keyrow { display: flex; gap: 6px; margin-bottom: 14px; } .dialog .keyrow input { margin: 0; flex: 1; min-width: 0; } +.dialog .snip { position: relative; margin-top: 6px; } +.dialog .snip pre { margin: 0; padding: 10px 10px; padding-right: 64px; max-height: 260px; overflow: auto; + font: 12px/1.45 var(--mono); background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; white-space: pre; } +.dialog .snip button { position: absolute; top: 6px; right: 6px; } +#cx-keycmd { white-space: pre-wrap; overflow-wrap: anywhere; } .dialog .actions { display: flex; justify-content: flex-end; } .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; } @@ -174,7 +184,7 @@ pre { - + @@ -281,10 +291,23 @@ pre {
- @@ -343,16 +366,54 @@ async function copyText(text) { t.remove(); return ok; } } +let CONNECT = null; function closeConnect() { $("connect-modal").classList.remove("show"); $("cx-key").value = ""; $("cx-key").type = "password"; $("cx-show").textContent = "Show"; + CONNECT = null; +} +// opencode's provider block for the address typed in. The server sends the block from +// the same builder as `llmhost opencode-config`; only what depends on the address is +// 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(/\/+$/, ""); + let host = ""; + try { host = new URL(url).hostname; } catch (e) {} + if (url && !/\/v1$/.test(url)) url += "/v1"; + const label = host || "server"; + const prov = "llmhost-" + (host.split(".")[0] || "server").toLowerCase().replace(/[^a-z0-9-]/g, "-"); + const keyfile = `~/.config/opencode/${prov}.key`; + const block = JSON.parse(JSON.stringify(CONNECT.opencode)); + block.name = block.name.replace("LABEL", label); + block.options.baseURL = url || "https:///v1"; + block.options.apiKey = `{file:${keyfile}}`; + for (const m of Object.values(block.models || {})) if (m.name) m.name = m.name.replace("LABEL", label); + $("cx-block").textContent = JSON.stringify({ [prov]: block }, null, 2); + $("cx-keycmd").textContent = + `mkdir -p ~/.config/opencode && printf 'API key: ' && stty -echo && read -r k; stty echo; echo\n` + + `printf '%s\\n' "$k" > ${keyfile} && chmod 600 ${keyfile}; unset k`; + $("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/key"); } catch (e) { if (e.message !== "unauthorized") toast("Couldn't load: " + e.message); return; } + 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"); +}); $("cx-copy").onclick = async () => toast(await copyText($("cx-key").value) ? "Copied" : "Couldn't copy; select it and copy by hand"); $("cx-show").onclick = () => { const k = $("cx-key"), hide = k.type === "text"; diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 3a32e56..a327ffd 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -517,11 +517,17 @@ def make_handler(sampler, key, oidc=None): elif path == "/api/status": if self.authed(): self.send_json(200, sampler.snapshot()) - elif path == "/api/key": - # For handing to clients. Behind the same sign-in as everything else here; - # send_json marks it no-store. + 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. if self.authed(): - self.send_json(200, {"key": key}) + 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}) elif path == "/api/logs": if self.authed(): lines = [l for l in service.logs("model", 1500) diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.py index 851f31c..b020340 100644 --- a/tests/test_dashboard_auth.py +++ b/tests/test_dashboard_auth.py @@ -98,10 +98,17 @@ check("config reports key mode", st == 200 and json.loads(body)["mode"] == "key" 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) -check("/api/key needs the key", req(srv, "GET", "/api/key")[0] == 401) -st, h, body, _ = req(srv, "GET", "/api/key", {"Authorization": f"Bearer {KEY}"}) -check("/api/key returns it", st == 200 and json.loads(body) == {"key": KEY}, body) -check("/api/key isn't cached", h.get("cache-control") == "no-store", h) +paths.save_config(harness.config()) +check("/api/connect needs the key", req(srv, "GET", "/api/connect")[0] == 401) +st, h, body, _ = req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"}) +cx = json.loads(body) +check("/api/connect returns the key", st == 200 and cx["key"] == KEY, body[:200]) +check("/api/connect isn't cached", h.get("cache-control") == "no-store", h) +blk = cx["opencode"] +check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk/openai-compatible", blk) +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)) srv.shutdown() print("\n2. OIDC mode refuses the key and unsigned visitors") @@ -169,10 +176,10 @@ st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, 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("/api/key refused without a session", req(srv, "GET", "/api/key", PUB_HOST)[0] == 401) -check("/api/key refused for the key alone", req(srv, "GET", "/api/key", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401) -st, _, body, _ = req(srv, "GET", "/api/key", {**PUB_HOST, "Cookie": sess}) -check("signed in: /api/key returns it", st == 200 and json.loads(body) == {"key": KEY}, body) +check("/api/connect refused without a session", req(srv, "GET", "/api/connect", PUB_HOST)[0] == 401) +check("/api/connect refused for the key alone", req(srv, "GET", "/api/connect", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401) +st, _, body, _ = req(srv, "GET", "/api/connect", {**PUB_HOST, "Cookie": sess}) +check("signed in: /api/connect returns the key", st == 200 and json.loads(body)["key"] == KEY, body[:200]) check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions) print("\n5. sign-ins that must fail")