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 <noreply@anthropic.com>
This commit is contained in:
neil 2026-11-05 23:03:56 -08:00
parent 6fd82448c5
commit 04ff14c58f
4 changed files with 93 additions and 18 deletions

View file

@ -112,8 +112,9 @@ It ends by printing the two Pangolin HTTP resources to create, both pointing at
| dashboard, at the `--public-url` host | `<LAN IP>:<web port>` | llm-host, through your OIDC provider | | dashboard, at the `--public-url` host | `<LAN IP>:<web port>` | llm-host, through your OIDC provider |
| API, at a host of your choice | `<LAN IP>:<API port>` | llm-host, with the API key | | API, at a host of your choice | `<LAN IP>:<API port>` | llm-host, with the API key |
Clients then use `https://<API host>/v1` with the key from `llmhost key`, or from the dashboard's **API key** button, Clients then use `https://<API host>/v1` with the key from `llmhost key`, or from the dashboard's **Connect** button.
which shows it to anyone signed in, with a copy 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: For Authelia, the client looks like this:

View file

@ -158,8 +158,18 @@ pre {
background: var(--panel-2); color: var(--text); margin-bottom: 12px; 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 .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 { display: flex; gap: 6px; margin-bottom: 14px; }
.dialog .keyrow input { margin: 0; flex: 1; min-width: 0; } .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; } .dialog .actions { display: flex; justify-content: flex-end; }
.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg); .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; } padding: 8px 14px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; }
@ -174,7 +184,7 @@ pre {
<span class="spacer"></span> <span class="spacer"></span>
<span class="meta" id="uptime"></span> <span class="meta" id="uptime"></span>
<span class="meta" id="whoami" hidden></span> <span class="meta" id="whoami" hidden></span>
<button id="connect" title="The API key, for clients">API key</button> <button id="connect" title="The API key, and how to add this server to opencode">Connect</button>
<button id="logout" title="Forget API key">Sign out</button> <button id="logout" title="Forget API key">Sign out</button>
</header> </header>
@ -281,10 +291,23 @@ pre {
</div> </div>
</div> </div>
<div class="overlay" id="connect-modal"> <div class="overlay" id="connect-modal">
<div class="dialog" role="dialog" aria-modal="true" aria-labelledby="connect-title"> <div class="dialog wide" role="dialog" aria-modal="true" aria-labelledby="connect-title">
<h3 id="connect-title">API key</h3> <h3 id="connect-title">Connect</h3>
<h4>API key</h4>
<p>For OpenAI-compatible clients, sent as <code>Authorization: Bearer &lt;key&gt;</code>. Use the model name <code>default</code>, which always means the loaded model.</p> <p>For OpenAI-compatible clients, sent as <code>Authorization: Bearer &lt;key&gt;</code>. Use the model name <code>default</code>, which always means the loaded model.</p>
<div class="keyrow"><input id="cx-key" type="password" readonly autocomplete="off" aria-label="API key"><button id="cx-show">Show</button><button id="cx-copy">Copy</button></div> <div class="keyrow"><input id="cx-key" type="password" readonly autocomplete="off" aria-label="API key"><button id="cx-show">Show</button><button id="cx-copy">Copy</button></div>
<h4>Add to opencode</h4>
<ol>
<li>The API's address, as this machine reaches it:
<div class="keyrow" style="margin:6px 0 0"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
placeholder="https://llm-api.example.com/v1" aria-label="API base URL"></div></li>
<li>Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
<div class="snip"><pre id="cx-keycmd"></pre><button class="small" data-copy="cx-keycmd">Copy</button></div></li>
<li>Merge this into <code>~/.config/opencode/opencode.json</code>, under <code>"provider"</code>:
<div class="snip"><pre id="cx-block"></pre><button class="small" data-copy="cx-block">Copy</button></div></li>
<li>Pick <b id="cx-pick"></b> in opencode's model list.</li>
</ol>
<div class="actions"><button id="cx-close">Close</button></div> <div class="actions"><button id="cx-close">Close</button></div>
</div> </div>
</div> </div>
@ -343,16 +366,54 @@ async function copyText(text) {
t.remove(); return ok; t.remove(); return ok;
} }
} }
let CONNECT = null;
function closeConnect() { function closeConnect() {
$("connect-modal").classList.remove("show"); $("connect-modal").classList.remove("show");
$("cx-key").value = ""; $("cx-key").type = "password"; $("cx-show").textContent = "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://<API host>/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 () => { $("connect").onclick = async () => {
let c; 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; $("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(); $("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-copy").onclick = async () => toast(await copyText($("cx-key").value) ? "Copied" : "Couldn't copy; select it and copy by hand");
$("cx-show").onclick = () => { $("cx-show").onclick = () => {
const k = $("cx-key"), hide = k.type === "text"; const k = $("cx-key"), hide = k.type === "text";

View file

@ -517,11 +517,17 @@ def make_handler(sampler, key, oidc=None):
elif path == "/api/status": elif path == "/api/status":
if self.authed(): if self.authed():
self.send_json(200, sampler.snapshot()) self.send_json(200, sampler.snapshot())
elif path == "/api/key": elif path == "/api/connect":
# For handing to clients. Behind the same sign-in as everything else here; # What the Connect dialog hands to clients: the key, and opencode's provider
# send_json marks it no-store. # 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(): 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": elif path == "/api/logs":
if self.authed(): if self.authed():
lines = [l for l in service.logs("model", 1500) lines = [l for l in service.logs("model", 1500)

View file

@ -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 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("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("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) paths.save_config(harness.config())
st, h, body, _ = req(srv, "GET", "/api/key", {"Authorization": f"Bearer {KEY}"}) check("/api/connect needs the key", req(srv, "GET", "/api/connect")[0] == 401)
check("/api/key returns it", st == 200 and json.loads(body) == {"key": KEY}, body) st, h, body, _ = req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})
check("/api/key isn't cached", h.get("cache-control") == "no-store", h) 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() srv.shutdown()
print("\n2. OIDC mode refuses the key and unsigned visitors") 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) check("POST from another origin -> 403", st == 403, st)
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC}) 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("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/connect refused without a session", req(srv, "GET", "/api/connect", 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) 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/key", {**PUB_HOST, "Cookie": sess}) st, _, body, _ = req(srv, "GET", "/api/connect", {**PUB_HOST, "Cookie": sess})
check("signed in: /api/key returns it", st == 200 and json.loads(body) == {"key": KEY}, body) 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) check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions)
print("\n5. sign-ins that must fail") print("\n5. sign-ins that must fail")