Split the internet upgrades: API-only tunnel, OIDC, authenticator codes, expose-dashboard
install-newt now sets up the tunnel for the API only; the dashboard stays on the LAN. Dashboard sign-in is its own step: install-oidc (the OIDC flow, split out) or install-otp, which pairs authenticator apps with a QR code in the terminal (stdlib QR encoder, TOTP per RFC 6238) so a code also opens the dashboard, with replay and lockout rules. expose-dashboard walks through publishing the dashboard, only after install-newt, and warns while it's protected by the API key alone; with codes it offers to switch the key off for the dashboard. Each install-* has a remove-*. Also opencode-install.sh: a standalone script, fetched from the repo, that installs opencode if needed, saves the API key to a 0600 file and adds the provider to opencode.json for new and existing configs. /v1/models reports whether the model reasons, for that script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e6ff4ce909
commit
c8b70afdbf
20 changed files with 1715 additions and 239 deletions
|
|
@ -171,6 +171,9 @@ pre {
|
|||
.dialog .snip button { position: absolute; top: 6px; right: 6px; }
|
||||
#cx-keycmd { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.dialog .actions { display: flex; justify-content: flex-end; }
|
||||
.dialog details.manual { margin-bottom: 12px; font-size: 13px; }
|
||||
.dialog details.manual summary { cursor: pointer; color: var(--muted); margin-bottom: 8px; }
|
||||
#cx-install { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg);
|
||||
padding: 8px 14px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; }
|
||||
.toast.show { opacity: 1; }
|
||||
|
|
@ -278,9 +281,16 @@ pre {
|
|||
|
||||
<div class="overlay" id="auth">
|
||||
<form class="dialog" id="auth-form">
|
||||
<h3>API key</h3>
|
||||
<p>Enter the API key from <code>~/.config/llm-host/api_key</code> on the server (or run <code>llmhost key</code>). It's kept in this browser only.</p>
|
||||
<input id="auth-key" type="password" autocomplete="current-password" placeholder="sk-…" required>
|
||||
<h3>Sign in</h3>
|
||||
<div id="auth-key-part">
|
||||
<p>Enter the API key from <code>~/.config/llm-host/api_key</code> on the server (or run <code>llmhost key</code>). It's kept in this browser only.</p>
|
||||
<input id="auth-key" type="password" autocomplete="current-password" placeholder="sk-…" aria-label="API key">
|
||||
</div>
|
||||
<div id="auth-otp-part" hidden>
|
||||
<p id="auth-otp-text">Or a code from your authenticator app:</p>
|
||||
<input id="auth-code" inputmode="numeric" autocomplete="one-time-code" maxlength="7" placeholder="123456"
|
||||
aria-label="Authenticator code">
|
||||
</div>
|
||||
<div class="err" id="auth-err"></div>
|
||||
<button class="primary" type="submit">Continue</button>
|
||||
</form>
|
||||
|
|
@ -298,10 +308,16 @@ pre {
|
|||
<div class="keyrow"><input id="cx-key" type="password" readonly autocomplete="off" aria-label="API key"><button id="cx-show">Show</button><button id="cx-copy">Copy</button></div>
|
||||
|
||||
<h4>Add to opencode</h4>
|
||||
<p>The API's address, as the machine running opencode reaches it:</p>
|
||||
<div class="keyrow"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
|
||||
placeholder="https://llm-api.example.com" aria-label="API base URL"></div>
|
||||
<p>Then run this there, or send it to whoever you're giving access, with the key. It needs only the API, not this
|
||||
dashboard: it installs opencode if it's missing, asks for the key (hidden), saves it, and adds this server to
|
||||
<code>opencode.json</code>, keeping their other settings:</p>
|
||||
<div class="snip" style="margin-bottom:14px"><pre id="cx-install"></pre><button class="small" data-copy="cx-install">Copy</button></div>
|
||||
<details class="manual">
|
||||
<summary>Or set it up by hand</summary>
|
||||
<ol>
|
||||
<li>The API's address, as this machine reaches it:
|
||||
<div class="keyrow" style="margin:6px 0 0"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
|
||||
placeholder="https://llm-api.example.com/v1" aria-label="API base URL"></div></li>
|
||||
<li>Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
|
||||
<div class="snip"><pre id="cx-keycmd"></pre><button class="small" data-copy="cx-keycmd">Copy</button></div></li>
|
||||
<li>Put this in <code>~/.config/opencode/opencode.json</code>. If the file is empty or missing, paste the whole thing;
|
||||
|
|
@ -310,6 +326,7 @@ pre {
|
|||
<div class="snip"><pre id="cx-block"></pre><button class="small" data-copy="cx-block">Copy</button></div></li>
|
||||
<li>Pick <b id="cx-pick"></b> in opencode's model list.</li>
|
||||
</ol>
|
||||
</details>
|
||||
<div class="actions"><button id="cx-close">Close</button></div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -335,9 +352,14 @@ function toast(msg) {
|
|||
|
||||
async function api(path, opts = {}) {
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
if (AUTH.mode === "key") headers["Authorization"] = "Bearer " + KEY;
|
||||
const useKey = AUTH.mode === "key" && KEY && AUTH.key !== false;
|
||||
if (useKey) headers["Authorization"] = "Bearer " + KEY;
|
||||
const r = await fetch(path, { ...opts, headers, credentials: "same-origin" });
|
||||
if (r.status === 401) { showAuth(AUTH.mode === "key" ? "That key was rejected." : ""); throw new Error("unauthorized"); }
|
||||
if (r.status === 401) {
|
||||
if (useKey) showAuth("That key was rejected.");
|
||||
else { AUTH.user = null; $("whoami").hidden = true; showAuth(""); }
|
||||
throw new Error("unauthorized");
|
||||
}
|
||||
const body = await r.json();
|
||||
if (!r.ok) throw new Error(body.error || r.statusText);
|
||||
return body;
|
||||
|
|
@ -349,12 +371,38 @@ function showAuth(err = "") {
|
|||
$("auth").classList.add("show"); $("auth-oidc-go").focus();
|
||||
return;
|
||||
}
|
||||
$("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus();
|
||||
// Key mode: the API key (unless it's switched off for the dashboard) and, after
|
||||
// `llmhost install-otp`, a code from an authenticator app.
|
||||
const keyOn = AUTH.key !== false;
|
||||
$("auth-key-part").hidden = !keyOn;
|
||||
$("auth-otp-part").hidden = !AUTH.otp;
|
||||
$("auth-otp-text").textContent = keyOn ? "Or a code from your authenticator app:" : "Enter a code from your authenticator app:";
|
||||
$("auth-err").textContent = err; $("auth").classList.add("show");
|
||||
(keyOn ? $("auth-key") : $("auth-code")).focus();
|
||||
}
|
||||
$("auth-form").addEventListener("submit", (e) => {
|
||||
function signedIn(user, name) {
|
||||
AUTH.user = user; AUTH.name = name;
|
||||
$("whoami").textContent = name || user; $("whoami").hidden = !user;
|
||||
}
|
||||
$("auth-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
KEY = $("auth-key").value.trim();
|
||||
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
|
||||
const code = AUTH.otp ? $("auth-code").value.replace(/\D/g, "") : "";
|
||||
if (code) {
|
||||
let r, body = {};
|
||||
try {
|
||||
r = await fetch("/auth/otp", { method: "POST", credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }) });
|
||||
body = await r.json();
|
||||
} catch (err) { $("auth-err").textContent = "Couldn't reach the dashboard."; return; }
|
||||
$("auth-code").value = "";
|
||||
if (!r.ok) { $("auth-err").textContent = body.error || "That code didn't work."; return; }
|
||||
signedIn("authenticator", "Authenticator app");
|
||||
} else {
|
||||
const k = $("auth-key").value.trim();
|
||||
if (!k || AUTH.key === false) { $("auth-err").textContent = AUTH.otp ? "Enter a code from your authenticator app." : "Enter the API key."; return; }
|
||||
KEY = k;
|
||||
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
|
||||
}
|
||||
$("auth").classList.remove("show");
|
||||
poll();
|
||||
});
|
||||
|
|
@ -402,6 +450,9 @@ function renderOpencode() {
|
|||
// One line: pasted as two, the first line's `read` would swallow the second as the key.
|
||||
`mkdir -p ~/.config/opencode && printf 'API key: ' && stty -echo && read -r k; stty echo; echo; ` +
|
||||
`[ -n "$k" ] && (umask 077 && printf '%s\\n' "$k" > ${keyfile}) && echo "saved ${keyfile}"; unset k`;
|
||||
$("cx-install").textContent = url
|
||||
? `/bin/bash -c "$(curl -fsSL ${CONNECT.installer})" -- --url ${url.replace(/\/v1$/, "")}`
|
||||
: "Type the API's address above first.";
|
||||
$("cx-pick").textContent = `${block.name} → ${Object.values(block.models)[0]?.name || CONNECT.model}`;
|
||||
try { localStorage.setItem("llmhost-api-url", $("cx-url").value.trim()); } catch (e) {}
|
||||
}
|
||||
|
|
@ -438,7 +489,9 @@ $("logout").onclick = async () => {
|
|||
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); closeConnect(); showAuth();
|
||||
return;
|
||||
}
|
||||
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; closeConnect(); showAuth();
|
||||
try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null;
|
||||
if (AUTH.user) { try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {} }
|
||||
signedIn(null); clearTimeout(pollTimer); closeConnect(); showAuth();
|
||||
};
|
||||
|
||||
const fmt = {
|
||||
|
|
@ -829,10 +882,10 @@ $("logs").addEventListener("toggle", () => {
|
|||
let pollTimer = null;
|
||||
async function poll() {
|
||||
clearTimeout(pollTimer);
|
||||
if (AUTH.mode === "key" ? !KEY : !AUTH.user) { showAuth(); return; }
|
||||
if (AUTH.mode === "key" ? !(KEY && AUTH.key !== false) && !AUTH.user : !AUTH.user) { showAuth(); return; }
|
||||
try { render(await api("/api/status")); }
|
||||
catch (e) {
|
||||
if (e.message === "unauthorized" && AUTH.mode === "oidc") return; // session over; wait for sign-in
|
||||
if (e.message === "unauthorized" && !(AUTH.mode === "key" && KEY)) return; // session over; wait for sign-in
|
||||
if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; }
|
||||
}
|
||||
pollTimer = setTimeout(poll, 2000);
|
||||
|
|
@ -843,10 +896,8 @@ async function poll() {
|
|||
const r = await fetch("/auth/config", { credentials: "same-origin" });
|
||||
if (r.ok) AUTH = await r.json();
|
||||
} catch (e) {}
|
||||
if (AUTH.mode === "oidc") {
|
||||
$("logout").title = "Sign out of this dashboard";
|
||||
if (AUTH.user) { $("whoami").textContent = AUTH.name || AUTH.user; $("whoami").hidden = false; }
|
||||
}
|
||||
if (AUTH.mode === "oidc" || AUTH.otp) $("logout").title = "Sign out of this dashboard";
|
||||
if (AUTH.user) signedIn(AUTH.user, AUTH.name);
|
||||
poll();
|
||||
})();
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
"""Dashboard: status, metrics and model switching. Stdlib only.
|
||||
|
||||
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or,
|
||||
when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py).
|
||||
Serves index.html and a JSON API on cfg["web_port"]. Who gets in:
|
||||
- by default, the API key (sent as a Bearer header by the page);
|
||||
- after `llmhost install-otp`, also a code from a paired authenticator app, which starts a
|
||||
session (sessions.py) -- and the key can be switched off here with dashboard_key_login;
|
||||
- after `llmhost install-oidc`, only people signed in through the OIDC provider (oidc.py).
|
||||
"""
|
||||
import hmac
|
||||
import html
|
||||
|
|
@ -18,6 +21,8 @@ from pathlib import Path
|
|||
|
||||
from .. import hfcache, hw, opencode, paths, plan, service
|
||||
from . import oidc as oidc_mod
|
||||
from . import sessions as sess_mod
|
||||
from .. import otp as otp_mod
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
SAMPLE_SECONDS = 2
|
||||
|
|
@ -412,7 +417,49 @@ class Sampler:
|
|||
threading.Thread(target=fn, args=("model",), daemon=True).start()
|
||||
|
||||
|
||||
def make_handler(sampler, key, oidc=None):
|
||||
DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too
|
||||
|
||||
|
||||
def raw_file_url(repo, ref, name):
|
||||
"""Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the
|
||||
/raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https."""
|
||||
m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "")
|
||||
if not m:
|
||||
return None
|
||||
host, path = m.group(1), m.group(2)
|
||||
if host.lower() == "github.com":
|
||||
return f"https://raw.githubusercontent.com/{path}/{ref}/{name}"
|
||||
return f"https://{host}/{path}/raw/branch/{ref}/{name}"
|
||||
|
||||
|
||||
_installer = None
|
||||
|
||||
|
||||
def installer_url():
|
||||
"""The opencode installer's URL in the repo this server was installed from, so the
|
||||
command the Connect dialog gives out works for people who can't reach this dashboard
|
||||
(an API-only tunnel) and follows a fork. Falls back to the main repo."""
|
||||
global _installer
|
||||
if _installer is None:
|
||||
import subprocess
|
||||
def git(*args):
|
||||
try:
|
||||
r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5)
|
||||
return r.stdout.strip() if r.returncode == 0 else ""
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return ""
|
||||
ref = git("rev-parse", "--abbrev-ref", "HEAD")
|
||||
_installer = (raw_file_url(git("config", "--get", "remote.origin.url"),
|
||||
ref if ref and ref != "HEAD" else "main", "opencode-install.sh")
|
||||
or raw_file_url(DEFAULT_REPO, "main", "opencode-install.sh"))
|
||||
return _installer
|
||||
|
||||
|
||||
def make_handler(sampler, key, oidc=None, otp=None, key_login=True):
|
||||
"""oidc: an oidc.OIDC, which then decides alone. Otherwise the API key (unless
|
||||
key_login is off) and, with otp (an otp.Verifier), authenticator codes."""
|
||||
sessions = sess_mod.Sessions() # authenticator-code sign-ins, in key mode
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "llm-host"
|
||||
|
||||
|
|
@ -440,11 +487,45 @@ def make_handler(sampler, key, oidc=None):
|
|||
return True
|
||||
h = self.headers.get("Authorization", "")
|
||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
||||
if hmac.compare_digest(tok.encode(), key.encode()):
|
||||
if key_login and tok and hmac.compare_digest(tok.encode(), key.encode()):
|
||||
return True
|
||||
if sessions.get(self.headers.get("Cookie", "")) is not None:
|
||||
if self.command == "POST" and not self.same_host():
|
||||
self.send_json(403, {"error": "cross-origin request refused"})
|
||||
return False
|
||||
return True
|
||||
self.send_json(401, {"error": "unauthorized"})
|
||||
return False
|
||||
|
||||
def same_host(self):
|
||||
"""Key mode's check for cookie-authenticated POSTs: the page that sent it must
|
||||
be this dashboard, by whatever name it was reached (LAN or tunnel)."""
|
||||
o = self.headers.get("Origin") or self.headers.get("Referer") or ""
|
||||
netloc = urllib.parse.urlsplit(o).netloc.lower()
|
||||
return bool(netloc) and netloc == (self.headers.get("Host") or "").lower()
|
||||
|
||||
def via_https(self):
|
||||
# Behind the tunnel, HTTPS ends at the reverse proxy, which says so here. Only
|
||||
# used for the cookie's Secure flag, so a forged header can only weaken that.
|
||||
return self.headers.get("X-Forwarded-Proto", "").lower() == "https"
|
||||
|
||||
def read_json(self):
|
||||
try:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
return json.loads(self.rfile.read(min(n, 65536)) or b"{}") if n else {}
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def send_json_cookie(self, code, obj, cookie):
|
||||
body = json.dumps(obj).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def redirect(self, url, cookies=()):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", url)
|
||||
|
|
@ -475,8 +556,11 @@ def make_handler(sampler, key, oidc=None):
|
|||
|
||||
def auth_get(self, path, query):
|
||||
if path == "/auth/config":
|
||||
s = oidc.session(self.headers.get("Cookie", "")) if oidc else None
|
||||
return self.send_json(200, {"mode": "oidc" if oidc else "key",
|
||||
if oidc:
|
||||
s = oidc.session(self.headers.get("Cookie", ""))
|
||||
return self.send_json(200, {"mode": "oidc", "user": s and s["user"], "name": s and s["name"]})
|
||||
s = sessions.get(self.headers.get("Cookie", ""))
|
||||
return self.send_json(200, {"mode": "key", "key": key_login, "otp": otp is not None,
|
||||
"user": s and s["user"], "name": s and s["name"]})
|
||||
if not oidc:
|
||||
return self.send_json(404, {"error": "not found"})
|
||||
|
|
@ -527,7 +611,8 @@ def make_handler(sampler, key, oidc=None):
|
|||
cfg = paths.load_config() or sampler.cfg
|
||||
block = opencode.provider_block(cfg, "HOST", "KEYFILE", "LABEL")
|
||||
self.send_json(200, {"key": key, "api_port": cfg["api_port"],
|
||||
"model": plan.SERVED_ALIAS, "opencode": block})
|
||||
"model": plan.SERVED_ALIAS, "opencode": block,
|
||||
"installer": installer_url()})
|
||||
elif path == "/api/logs":
|
||||
if self.authed():
|
||||
lines = [l for l in service.logs("model", 1500)
|
||||
|
|
@ -538,17 +623,29 @@ def make_handler(sampler, key, oidc=None):
|
|||
|
||||
def do_POST(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
if path == "/auth/logout" and oidc:
|
||||
if not oidc.same_origin(self.headers):
|
||||
if path == "/auth/logout":
|
||||
if not (oidc.same_origin(self.headers) if oidc else self.same_host()):
|
||||
return self.send_json(403, {"error": "cross-origin request refused"})
|
||||
oidc.end(self.headers.get("Cookie", ""))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0))
|
||||
self.send_header("Content-Length", "11")
|
||||
self.end_headers()
|
||||
self.wfile.write(b'{"ok": true}')
|
||||
return
|
||||
(oidc or sessions).end(self.headers.get("Cookie", ""))
|
||||
clear = (oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0) if oidc
|
||||
else sess_mod.cookie(sess_mod.SESSION_COOKIE, "", 0, self.via_https()))
|
||||
return self.send_json_cookie(200, {"ok": True}, clear)
|
||||
if path == "/auth/otp":
|
||||
if oidc or otp is None:
|
||||
return self.send_json(404, {"error": "not found"})
|
||||
if not self.same_host():
|
||||
return self.send_json(403, {"error": "cross-origin request refused"})
|
||||
data = self.read_json()
|
||||
result = otp.check(str((data or {}).get("code", "")))
|
||||
if result == "locked":
|
||||
return self.send_json(429, {"error": "too many wrong codes; try again in a few minutes",
|
||||
"retry_after": otp.locked_for()})
|
||||
if result != "ok":
|
||||
return self.send_json(401, {"error": "that code is wrong, expired or already used"})
|
||||
sid = sessions.create("authenticator", "Authenticator app")
|
||||
print("llm-host dashboard: signed in with an authenticator code", flush=True)
|
||||
return self.send_json_cookie(200, {"ok": True}, sess_mod.cookie(
|
||||
sess_mod.SESSION_COOKIE, sid, sess_mod.SESSION_TTL, self.via_https()))
|
||||
if not self.authed():
|
||||
return
|
||||
try:
|
||||
|
|
@ -588,11 +685,15 @@ def serve():
|
|||
key = paths.api_key()
|
||||
sampler = Sampler(cfg, key)
|
||||
threading.Thread(target=sampler.loop, daemon=True).start()
|
||||
auth = None
|
||||
auth = otp = None
|
||||
conf = cfg.get("dashboard_auth") or {}
|
||||
if conf.get("mode") == "oidc":
|
||||
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth))
|
||||
how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key"
|
||||
elif paths.OTP_SECRET_FILE.exists():
|
||||
otp = otp_mod.Verifier(paths.read_secret(paths.OTP_SECRET_FILE, "authenticator secret", "llmhost install-otp"))
|
||||
key_login = cfg.get("dashboard_key_login", True) or otp is None # never lock everyone out
|
||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth, otp, key_login))
|
||||
how = (f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else
|
||||
" or ".join((["API key"] if key_login else []) + (["authenticator code"] if otp else [])))
|
||||
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
|
||||
srv.serve_forever()
|
||||
|
|
|
|||
65
llmhost/web/sessions.py
Normal file
65
llmhost/web/sessions.py
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
"""Signed-in dashboard sessions, for OIDC and authenticator-code sign-in. Stdlib only.
|
||||
|
||||
A session is a random id in an HttpOnly, SameSite=Lax cookie; only its SHA-256 is kept,
|
||||
in memory, so a dashboard restart signs everyone out.
|
||||
"""
|
||||
import hashlib
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
SESSION_COOKIE = "llmhost_session"
|
||||
SESSION_TTL = 12 * 3600
|
||||
|
||||
|
||||
def parse_cookies(header: str) -> dict:
|
||||
out = {}
|
||||
for part in (header or "").split(";"):
|
||||
k, sep, v = part.strip().partition("=")
|
||||
if sep:
|
||||
out.setdefault(k, v)
|
||||
return out
|
||||
|
||||
|
||||
def cookie(name, value, max_age, secure, path="/"):
|
||||
attrs = [f"{name}={value}", f"Path={path}", f"Max-Age={max_age}", "HttpOnly", "SameSite=Lax"]
|
||||
if secure:
|
||||
attrs.append("Secure")
|
||||
return "; ".join(attrs)
|
||||
|
||||
|
||||
class Sessions:
|
||||
def __init__(self, ttl=SESSION_TTL):
|
||||
self.ttl = ttl
|
||||
self.lock = threading.Lock()
|
||||
self.items = {} # sha256(id) -> {user, name, exp}
|
||||
|
||||
@staticmethod
|
||||
def _h(sid: str) -> str:
|
||||
return hashlib.sha256(sid.encode()).hexdigest()
|
||||
|
||||
def create(self, user, name=None) -> str:
|
||||
sid = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with self.lock:
|
||||
for h in [h for h, s in self.items.items() if s["exp"] < now]:
|
||||
del self.items[h]
|
||||
self.items[self._h(sid)] = {"user": user, "name": name or user, "exp": now + self.ttl}
|
||||
return sid
|
||||
|
||||
def get(self, cookie_header: str):
|
||||
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
|
||||
if not sid:
|
||||
return None
|
||||
with self.lock:
|
||||
s = self.items.get(self._h(sid))
|
||||
if s and s["exp"] < time.time():
|
||||
del self.items[self._h(sid)]
|
||||
s = None
|
||||
return s
|
||||
|
||||
def end(self, cookie_header: str):
|
||||
sid = parse_cookies(cookie_header).get(SESSION_COOKIE)
|
||||
if sid:
|
||||
with self.lock:
|
||||
self.items.pop(self._h(sid), None)
|
||||
Loading…
Add table
Add a link
Reference in a new issue