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
|
|
@ -104,7 +104,8 @@ def run_server(cfg, entry, choice, args):
|
|||
controls = hfcache.template_controls(choice["repo"])
|
||||
srv = proxy.listen(port, proxy.make_handler(
|
||||
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
|
||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls)))
|
||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
|
||||
reasons=choice.get("reasoning", entry.get("reasoning"))))
|
||||
proxy.kill_stale(inner, VENV, "mlx_lm")
|
||||
|
||||
exe = str(VENV / "bin/mlx_lm.server")
|
||||
|
|
|
|||
|
|
@ -73,10 +73,12 @@ def _uncached(usage):
|
|||
|
||||
|
||||
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None,
|
||||
upstream_model="default_model", upstream_key=None):
|
||||
upstream_model="default_model", upstream_key=None, reasons=False):
|
||||
"""upstream_model: what the inner server calls the loaded model ("default_model" makes
|
||||
mlx_lm use the preloaded one; vLLM wants its --served-model-name). upstream_key: sent
|
||||
on to an inner server that checks keys itself (vLLM)."""
|
||||
on to an inner server that checks keys itself (vLLM). reasons: whether the model
|
||||
thinks, reported in /v1/models so a client setup (opencode-install.sh) can configure
|
||||
the model the way `llmhost opencode-config` does."""
|
||||
# Names a client may call the loaded model: its llm-host name, its repo id, and the
|
||||
# stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
|
||||
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
|
||||
|
|
@ -121,7 +123,8 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso
|
|||
return
|
||||
if self.path.startswith("/v1/models"):
|
||||
return self._json(200, {"object": "list", "data": [
|
||||
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context}]})
|
||||
{"id": served_name, "object": "model", "owned_by": "llm-host", "max_model_len": context,
|
||||
"reasoning": bool(reasons)}]})
|
||||
self._forward("GET", None)
|
||||
|
||||
def _model_ok(self, body):
|
||||
|
|
|
|||
|
|
@ -175,7 +175,8 @@ def run_server(cfg, entry, choice, args):
|
|||
srv = proxy.listen(port, proxy.make_handler(
|
||||
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
|
||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
|
||||
upstream_model=entry["name"], upstream_key=key))
|
||||
upstream_model=entry["name"], upstream_key=key,
|
||||
reasons=choice.get("reasoning", entry.get("reasoning"))))
|
||||
proxy.kill_stale(inner, VENV, "vllm")
|
||||
exe = str(VENV / "bin/vllm")
|
||||
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.
|
||||
|
|
|
|||
280
llmhost/cli.py
280
llmhost/cli.py
|
|
@ -8,6 +8,7 @@ import subprocess
|
|||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from . import hfcache, hw, opencode, paths, plan, service
|
||||
|
|
@ -118,8 +119,8 @@ def carried_settings(old, names):
|
|||
longer fit lose their setting along with their plan."""
|
||||
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
|
||||
out = {"reasoning": kept} if kept else {}
|
||||
for k in ("newt", "dashboard_auth"): # set by `llmhost install-newt`, not by the plan
|
||||
if old.get(k):
|
||||
for k in ("newt", "dashboard_auth", "dashboard_key_login"): # set by install-*/expose-dashboard, not the plan
|
||||
if old.get(k) is not None: # dashboard_key_login is False when it matters
|
||||
out[k] = old[k]
|
||||
return out
|
||||
|
||||
|
|
@ -351,7 +352,11 @@ def cmd_status(a):
|
|||
d = cfg.get("dashboard_auth") or {}
|
||||
if d.get("mode") == "oidc":
|
||||
who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])])
|
||||
say(f"public {d['public_url']} (sign-in via {d['issuer']}; {who})")
|
||||
say(f"sign-in OIDC via {d['issuer']} at {d['public_url']} ({who})")
|
||||
else:
|
||||
ways = (["API key"] if cfg.get("dashboard_key_login", True) or not paths.OTP_SECRET_FILE.exists() else []) \
|
||||
+ (["authenticator code"] if paths.OTP_SECRET_FILE.exists() else [])
|
||||
say(f"sign-in {' or '.join(ways)}")
|
||||
if cfg.get("newt"):
|
||||
say(f"tunnel newt -> {cfg['newt']['endpoint']}")
|
||||
|
||||
|
|
@ -534,25 +539,67 @@ def _check_url(label, url, bare=True):
|
|||
|
||||
|
||||
def cmd_install_newt(a):
|
||||
"""Upgrade a LAN install for the internet: newt tunnel + OIDC sign-in on the dashboard."""
|
||||
"""Reach the API from the internet through a Pangolin tunnel. The dashboard stays on
|
||||
the LAN: publishing it is a separate, deliberate step (`llmhost expose-dashboard`)."""
|
||||
from . import newt
|
||||
from .web import oidc
|
||||
cfg = _service_check()
|
||||
old_n, old_d = cfg.get("newt") or {}, cfg.get("dashboard_auth") or {}
|
||||
old_n = cfg.get("newt") or {}
|
||||
newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for
|
||||
|
||||
say("Pangolin site (Pangolin: Sites -> Add Site -> Newt):")
|
||||
endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint", a.endpoint, old_n.get("endpoint"), "--endpoint"))
|
||||
site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id")
|
||||
have_newt_secret = paths.NEWT_SECRET_FILE.exists() and old_n
|
||||
newt_secret = _ask(" Newt secret", None, "keep" if have_newt_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
|
||||
have_secret = paths.NEWT_SECRET_FILE.exists() and old_n
|
||||
newt_secret = _ask(" Newt secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
|
||||
|
||||
say("\nDashboard sign-in (an OIDC client registered with your provider):")
|
||||
public_url = _check_url("Dashboard URL", _ask(" Dashboard's public URL", a.public_url, old_d.get("public_url"), "--public-url"))
|
||||
newt.ensure_binary(say)
|
||||
if newt_secret != "keep":
|
||||
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
|
||||
cfg["newt"] = {"endpoint": endpoint, "id": site_id}
|
||||
paths.save_config(cfg)
|
||||
service.install("newt")
|
||||
if not service.restart("newt"):
|
||||
say("newt didn't start; see `llmhost logs --newt`.")
|
||||
ip = lan_ip()
|
||||
say(f"""
|
||||
Done. newt is running. In Pangolin, add an HTTP resource on this site for the API:
|
||||
<a host of your choice> -> http://{ip}:{cfg['api_port']}
|
||||
with Pangolin's own authentication off (llm-host checks the API key). Point it at {ip}, not
|
||||
localhost: requests from localhost count as local here.
|
||||
|
||||
Clients then use https://<that host>/v1 with the API key; for opencode, see the dashboard's
|
||||
Connect button, or opencode-install.sh in the llm-host repo.
|
||||
|
||||
The dashboard stays on your local network. To put it online too, first give it a sign-in
|
||||
that isn't the API key you hand out (`llmhost install-oidc` or `llmhost install-otp`), then
|
||||
run `llmhost expose-dashboard`. Undo the tunnel with: llmhost remove-newt""")
|
||||
|
||||
|
||||
def cmd_remove_newt(a):
|
||||
"""Back to LAN-only: stop and remove newt. The dashboard's sign-in is left as it is."""
|
||||
cfg = _service_check()
|
||||
if service.installed("newt"):
|
||||
service.uninstall("newt")
|
||||
shutil.rmtree(paths.NEWT_DIR, ignore_errors=True)
|
||||
paths.NEWT_SECRET_FILE.unlink(missing_ok=True)
|
||||
had = bool(cfg.pop("newt", None))
|
||||
paths.save_config(cfg)
|
||||
say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.")
|
||||
|
||||
|
||||
def cmd_install_oidc(a):
|
||||
"""Sign in to the dashboard through an OIDC provider instead of with the API key."""
|
||||
from .web import oidc
|
||||
cfg = _service_check()
|
||||
old_d = cfg.get("dashboard_auth") or {}
|
||||
say("Dashboard sign-in through OIDC (a client registered with your provider):")
|
||||
public_url = _check_url("Dashboard URL", _ask(" Dashboard's URL, as browsers reach it", a.public_url,
|
||||
old_d.get("public_url"), "--public-url"))
|
||||
issuer = _check_url("Issuer", _ask(" OIDC issuer", a.issuer, old_d.get("issuer"), "--issuer"), bare=False)
|
||||
client_id = _ask(" Client ID", a.client_id, old_d.get("client_id") or "llm-host", "--client-id")
|
||||
have_oidc_secret = paths.OIDC_SECRET_FILE.exists() and old_d
|
||||
oidc_secret = _ask(" Client secret", None, "keep" if have_oidc_secret else None, secret=True, env="LLMHOST_OIDC_SECRET")
|
||||
client_id = _ask(" Client ID (from your provider's client config)", a.client_id,
|
||||
old_d.get("client_id") or "llm-host", "--client-id")
|
||||
have_secret = paths.OIDC_SECRET_FILE.exists() and old_d
|
||||
secret = _ask(" Client secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_OIDC_SECRET")
|
||||
groups, users = a.allow_group or [], a.allow_user or []
|
||||
if not (groups or users):
|
||||
# A re-run keeps the allow list unless it's given again.
|
||||
|
|
@ -565,53 +612,168 @@ def cmd_install_newt(a):
|
|||
|
||||
dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url,
|
||||
"allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))}
|
||||
secret_for_check = paths.oidc_secret() if oidc_secret == "keep" else oidc_secret
|
||||
try:
|
||||
oidc.OIDC(dash, secret_for_check).discovery()
|
||||
oidc.OIDC(dash, paths.oidc_secret() if secret == "keep" else secret).discovery()
|
||||
except oidc.AuthError as e:
|
||||
sys.exit(str(e))
|
||||
|
||||
newt.ensure_binary(say)
|
||||
if newt_secret != "keep":
|
||||
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
|
||||
if oidc_secret != "keep":
|
||||
paths.save_secret(paths.OIDC_SECRET_FILE, oidc_secret)
|
||||
cfg["newt"] = {"endpoint": endpoint, "id": site_id}
|
||||
if secret != "keep":
|
||||
paths.save_secret(paths.OIDC_SECRET_FILE, secret)
|
||||
cfg["dashboard_auth"] = dash
|
||||
paths.save_config(cfg)
|
||||
|
||||
service.install("newt")
|
||||
if not service.restart("newt"):
|
||||
say("newt didn't start; see `llmhost logs --newt`.")
|
||||
_restart_if_running("web")
|
||||
ip = lan_ip()
|
||||
extra = ("\nAuthenticator codes (install-otp) are unused while OIDC is on; they come back with remove-oidc."
|
||||
if paths.OTP_SECRET_FILE.exists() else "")
|
||||
say(f"""
|
||||
Done. newt is running and the dashboard now signs in through {issuer};
|
||||
the API key no longer opens it (the API itself still uses the key).
|
||||
|
||||
In Pangolin, add two HTTP resources on this site, with Pangolin's own SSO off on both
|
||||
(llm-host checks the API key on one and signs people in on the other):
|
||||
dashboard {public_url} -> http://{ip}:{cfg['web_port']}
|
||||
API <a host of your choice> -> http://{ip}:{cfg['api_port']}
|
||||
Point them at {ip}, not localhost: requests from localhost count as local here.
|
||||
Done. The dashboard now signs in through {issuer}; the API key no longer opens it (the API
|
||||
itself still uses the key).
|
||||
|
||||
Register this redirect URI with your OIDC client: {public_url}/auth/callback
|
||||
Clients use https://<API host>/v1 with the API key (`llmhost key`).
|
||||
Undo all of this with: llmhost remove-newt""")
|
||||
|
||||
Sign-in happens at {public_url}, and visits by any other address are sent there, so the
|
||||
dashboard has to be reachable at that URL -- see `llmhost expose-dashboard`. If you can't
|
||||
get in, `llmhost remove-oidc` puts the API key back.{extra}""")
|
||||
|
||||
|
||||
def cmd_remove_newt(a):
|
||||
"""Back to a LAN-only install: stop newt, and the dashboard takes the API key again."""
|
||||
def cmd_remove_oidc(a):
|
||||
cfg = _service_check()
|
||||
if service.installed("newt"):
|
||||
service.uninstall("newt")
|
||||
shutil.rmtree(paths.NEWT_DIR, ignore_errors=True)
|
||||
paths.NEWT_SECRET_FILE.unlink(missing_ok=True)
|
||||
had = bool(cfg.pop("dashboard_auth", None))
|
||||
paths.OIDC_SECRET_FILE.unlink(missing_ok=True)
|
||||
had = bool(cfg.pop("newt", None)) | bool(cfg.pop("dashboard_auth", None))
|
||||
paths.save_config(cfg)
|
||||
_restart_if_running("web")
|
||||
say("Removed newt; the dashboard takes the API key again." if had else "newt wasn't installed.")
|
||||
after = "the API key" + (" or an authenticator code" if paths.OTP_SECRET_FILE.exists() else "")
|
||||
say(f"OIDC sign-in is off; the dashboard takes {after} again." if had else "OIDC sign-in wasn't on.")
|
||||
|
||||
|
||||
def _show_pairing(secret):
|
||||
from . import otp, qr
|
||||
uri = otp.pairing_uri(secret, default_host())
|
||||
say("\nScan this with an authenticator app (Google Authenticator, 1Password, Aegis, ...):\n")
|
||||
for row in qr.QR(uri).terminal():
|
||||
say(" " + row)
|
||||
say(f"\nOr enter this key by hand (time-based, 6 digits, 30 s): {otp.grouped(secret)}\n")
|
||||
|
||||
|
||||
def cmd_install_otp(a):
|
||||
"""Pair authenticator apps; their codes then also open the dashboard."""
|
||||
from . import otp
|
||||
cfg = _service_check()
|
||||
if not sys.stdin.isatty() or not sys.stdout.isatty():
|
||||
sys.exit("install-otp shows a QR code and asks for a code back, so run it in a terminal")
|
||||
existing = paths.OTP_SECRET_FILE.exists()
|
||||
if a.show:
|
||||
if not existing:
|
||||
sys.exit("no authenticator is paired yet; run `llmhost install-otp`")
|
||||
say("This is the existing pairing. Anyone who sees it can make codes, so keep it private.")
|
||||
_show_pairing(paths.read_secret(paths.OTP_SECRET_FILE, "authenticator secret", "llmhost install-otp"))
|
||||
say("Add it to as many apps or devices as you like; they all make the same codes.")
|
||||
return
|
||||
if existing and input("An authenticator is already paired. Replace it? Apps paired now stop working. "
|
||||
"(To add another device instead: llmhost install-otp --show) [y/N] ").strip().lower() not in ("y", "yes"):
|
||||
sys.exit("kept the existing pairing")
|
||||
|
||||
secret = otp.new_secret()
|
||||
_show_pairing(secret)
|
||||
for attempt in range(3):
|
||||
code = input("Enter the 6-digit code the app shows, to confirm: ").strip()
|
||||
if otp.matching_step(secret, code) is not None:
|
||||
break
|
||||
say("That code doesn't match. Check the phone's clock is set automatically, then try the current code.")
|
||||
else:
|
||||
sys.exit("not paired; nothing was changed")
|
||||
paths.save_secret(paths.OTP_SECRET_FILE, secret)
|
||||
cfg.pop("dashboard_key_login", None) # a new pairing starts with the key still working
|
||||
paths.save_config(cfg)
|
||||
_restart_if_running("web")
|
||||
oidc_on = (cfg.get("dashboard_auth") or {}).get("mode") == "oidc"
|
||||
say("""
|
||||
Paired. The dashboard's sign-in now also takes a code from the app, alongside the API key.
|
||||
To add another phone or app later: llmhost install-otp --show. To unpair: llmhost remove-otp."""
|
||||
+ ("\nOIDC sign-in is on, which takes precedence; codes work once it's removed (remove-oidc)." if oidc_on else ""))
|
||||
|
||||
|
||||
def cmd_remove_otp(a):
|
||||
cfg = _service_check()
|
||||
had = paths.OTP_SECRET_FILE.exists()
|
||||
paths.OTP_SECRET_FILE.unlink(missing_ok=True)
|
||||
cfg.pop("dashboard_key_login", None) # without codes, the key is the way in again
|
||||
paths.save_config(cfg)
|
||||
_restart_if_running("web")
|
||||
say("Unpaired; the dashboard takes the API key again (apps can delete the llm-host entry)." if had
|
||||
else "No authenticator was paired.")
|
||||
|
||||
|
||||
def _confirm(question):
|
||||
if not sys.stdin.isatty():
|
||||
return False
|
||||
return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
|
||||
|
||||
|
||||
def cmd_expose_dashboard(a):
|
||||
"""Walk through publishing the dashboard through newt, once it has a sign-in of its own."""
|
||||
cfg = _service_check()
|
||||
if not (cfg.get("newt") and service.installed("newt")):
|
||||
sys.exit("""The dashboard is published through the newt tunnel, which isn't set up yet.
|
||||
Run `llmhost install-newt` first, then come back here.""")
|
||||
d = cfg.get("dashboard_auth") or {}
|
||||
oidc_on = d.get("mode") == "oidc"
|
||||
otp_on = paths.OTP_SECRET_FILE.exists()
|
||||
key_on = cfg.get("dashboard_key_login", True)
|
||||
|
||||
if oidc_on:
|
||||
say(f"Sign-in: OIDC through {d['issuer']} -- good; only allowed accounts get in.")
|
||||
elif otp_on and not key_on:
|
||||
say("Sign-in: authenticator codes only -- good; the API key you hand out doesn't open it.")
|
||||
elif otp_on:
|
||||
say("""Sign-in: authenticator codes, and still the API key.
|
||||
Once the dashboard is public, anyone you've given the API key could also use it to stop,
|
||||
start or switch the model. Turning the key off for the dashboard leaves codes as the only
|
||||
way in there; the API itself keeps using the key.""")
|
||||
if a.disable_key_login or _confirm("Turn off API-key sign-in on the dashboard?"):
|
||||
cfg["dashboard_key_login"] = False
|
||||
paths.save_config(cfg)
|
||||
_restart_if_running("web")
|
||||
key_on = False
|
||||
say("Done: the dashboard now takes authenticator codes only.")
|
||||
else:
|
||||
say("""Sign-in: the API key only.
|
||||
That's the same key you hand to API users. Once the dashboard is public, any of them --
|
||||
or anyone the key leaks to -- could stop, start or switch the model. Give the dashboard
|
||||
its own sign-in first:
|
||||
llmhost install-oidc sign in through your OIDC provider (recommended)
|
||||
llmhost install-otp codes from an authenticator app""")
|
||||
if not (a.force or _confirm("Publish it anyway, behind the API key alone?")):
|
||||
sys.exit("Not published. Set up a sign-in, then run `llmhost expose-dashboard` again.")
|
||||
|
||||
public_url = d.get("public_url") if oidc_on else None
|
||||
if not public_url:
|
||||
public_url = _check_url("Dashboard URL", _ask("Public address for the dashboard", a.public_url, None,
|
||||
"--public-url"))
|
||||
host = urllib.parse.urlsplit(public_url).netloc
|
||||
ip = lan_ip()
|
||||
pangolin_auth = ("off (llm-host signs people in through your OIDC provider; a second login in front would"
|
||||
" get in the way)" if oidc_on else
|
||||
"your choice: off, or on as an extra layer in front of llm-host's own sign-in")
|
||||
say(f"""
|
||||
In Pangolin, on the same site as the API, add an HTTP resource:
|
||||
domain {host}
|
||||
target http://{ip}:{cfg['web_port']} (this machine's LAN address, not localhost)
|
||||
authentication {pangolin_auth}""")
|
||||
if oidc_on:
|
||||
say(f" and make sure your OIDC client allows the redirect URI {public_url}/auth/callback")
|
||||
if not sys.stdin.isatty():
|
||||
return
|
||||
input("\nPress Enter once the resource is saved, to check it from here... ")
|
||||
try:
|
||||
with urllib.request.urlopen(public_url + "/auth/config", timeout=15) as r:
|
||||
got = json.loads(r.read())
|
||||
ok = got.get("mode") in ("key", "oidc")
|
||||
except Exception as e:
|
||||
ok, got = False, e
|
||||
if ok:
|
||||
say(f"It works: {public_url} reaches this dashboard.")
|
||||
else:
|
||||
say(f"Couldn't reach this dashboard at {public_url} yet ({got}). A new resource's certificate can take a"
|
||||
f" minute; check the domain, the target and that the resource is enabled, then try the URL in a browser.")
|
||||
|
||||
|
||||
def cmd_download(a):
|
||||
|
|
@ -837,17 +999,29 @@ def main(argv=None):
|
|||
sub.add_parser("watch", help="show download and loading progress until the model is ready"
|
||||
).set_defaults(fn=cmd_watch)
|
||||
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
||||
s = sub.add_parser("install-newt", help="reach this server from the internet: newt tunnel + OIDC sign-in on the dashboard")
|
||||
s = sub.add_parser("install-newt", help="reach the API from the internet through a Pangolin tunnel (dashboard stays local)")
|
||||
s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com")
|
||||
s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)")
|
||||
s.add_argument("--public-url", help="the dashboard's public address, e.g. https://llm-dash.example.com")
|
||||
s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com")
|
||||
s.add_argument("--client-id", help="OIDC client ID (default llm-host; secret: prompted, or $LLMHOST_OIDC_SECRET)")
|
||||
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed into the dashboard (repeatable)")
|
||||
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed into the dashboard (repeatable)")
|
||||
s.set_defaults(fn=cmd_install_newt)
|
||||
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel, dashboard back to the API key"
|
||||
).set_defaults(fn=cmd_remove_newt)
|
||||
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt)
|
||||
s = sub.add_parser("install-oidc", help="sign in to the dashboard through an OIDC provider instead of the API key")
|
||||
s.add_argument("--public-url", help="the dashboard's address, e.g. https://llm-dash.example.com")
|
||||
s.add_argument("--issuer", help="OIDC provider, e.g. https://auth.example.com")
|
||||
s.add_argument("--client-id", help="OIDC client ID (secret: prompted, or $LLMHOST_OIDC_SECRET)")
|
||||
s.add_argument("--allow-group", action="append", metavar="GROUP", help="provider group allowed in (repeatable)")
|
||||
s.add_argument("--allow-user", action="append", metavar="USER", help="username allowed in (repeatable)")
|
||||
s.set_defaults(fn=cmd_install_oidc)
|
||||
sub.add_parser("remove-oidc", help="undo install-oidc: the dashboard takes the API key again"
|
||||
).set_defaults(fn=cmd_remove_oidc)
|
||||
s = sub.add_parser("install-otp", help="pair authenticator apps; their codes also open the dashboard")
|
||||
s.add_argument("--show", action="store_true", help="show the existing pairing again, to add another device")
|
||||
s.set_defaults(fn=cmd_install_otp)
|
||||
sub.add_parser("remove-otp", help="undo install-otp: unpair authenticator apps").set_defaults(fn=cmd_remove_otp)
|
||||
s = sub.add_parser("expose-dashboard", help="walk through publishing the dashboard through newt (after install-newt and a sign-in)")
|
||||
s.add_argument("--public-url", help="the dashboard's public address")
|
||||
s.add_argument("--disable-key-login", action="store_true", help="with authenticator codes set up, stop the API key opening the dashboard")
|
||||
s.add_argument("--force", action="store_true", help="publish even with only the API key protecting it")
|
||||
s.set_defaults(fn=cmd_expose_dashboard)
|
||||
s = sub.add_parser("download", help="download a model ahead of time")
|
||||
s.add_argument("model")
|
||||
s.set_defaults(fn=cmd_download)
|
||||
|
|
|
|||
104
llmhost/otp.py
Normal file
104
llmhost/otp.py
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
"""One-time codes from an authenticator app (TOTP, RFC 6238), for dashboard sign-in.
|
||||
|
||||
`llmhost install-otp` makes a secret, shows it as a QR code to pair the app(s), and once a
|
||||
code checks out stores it in ~/.config/llm-host/otp_secret (0600). The dashboard then
|
||||
accepts a current code wherever it asks for the API key. Stdlib only.
|
||||
|
||||
The parameters are the ones every authenticator app defaults to -- SHA-1, 6 digits, 30
|
||||
seconds -- since some apps ignore anything else in the pairing link.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
from collections import deque
|
||||
|
||||
STEP = 30
|
||||
DIGITS = 6
|
||||
WINDOW = 1 # accept the previous and next step too: clocks drift
|
||||
MAX_FAILURES = 5 # wrong codes allowed in FAIL_WINDOW before codes are refused
|
||||
FAIL_WINDOW = 300
|
||||
ISSUER = "llm-host"
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=")
|
||||
|
||||
|
||||
def _key(secret_b32: str) -> bytes:
|
||||
s = secret_b32.strip().replace(" ", "").upper()
|
||||
return base64.b32decode(s + "=" * (-len(s) % 8))
|
||||
|
||||
|
||||
def code_at(secret_b32: str, t: float, digits=DIGITS, step=STEP) -> str:
|
||||
counter = int(t // step)
|
||||
h = hmac.new(_key(secret_b32), struct.pack(">Q", counter), hashlib.sha1).digest()
|
||||
o = h[-1] & 0x0F
|
||||
n = (struct.unpack(">I", h[o:o + 4])[0] & 0x7FFFFFFF) % 10 ** digits
|
||||
return str(n).zfill(digits)
|
||||
|
||||
|
||||
def pairing_uri(secret_b32: str, account: str) -> str:
|
||||
label = urllib.parse.quote(f"{ISSUER}:{account}", safe=":@")
|
||||
q = urllib.parse.urlencode({"secret": secret_b32, "issuer": ISSUER, "algorithm": "SHA1",
|
||||
"digits": DIGITS, "period": STEP})
|
||||
return f"otpauth://totp/{label}?{q}"
|
||||
|
||||
|
||||
def grouped(secret_b32: str) -> str:
|
||||
"""The secret in groups of four, for typing into an app that can't scan."""
|
||||
return " ".join(secret_b32[i:i + 4] for i in range(0, len(secret_b32), 4))
|
||||
|
||||
|
||||
def matching_step(secret_b32: str, code: str, now=None):
|
||||
"""The time step `code` belongs to (within the drift window), or None."""
|
||||
code = "".join(ch for ch in str(code) if ch.isdigit())
|
||||
if len(code) != DIGITS:
|
||||
return None
|
||||
now = time.time() if now is None else now
|
||||
base = int(now // STEP)
|
||||
for step in range(base - WINDOW, base + WINDOW + 1):
|
||||
if hmac.compare_digest(code_at(secret_b32, step * STEP), code):
|
||||
return step
|
||||
return None
|
||||
|
||||
|
||||
class Verifier:
|
||||
"""Checks dashboard sign-in codes: each code works once, and after MAX_FAILURES wrong
|
||||
ones within FAIL_WINDOW, every code is refused until the window passes. The limit is
|
||||
global rather than per address because behind a tunnel every request comes from the
|
||||
same place; at worst a guesser locks codes out for a few minutes, and the API key
|
||||
still works."""
|
||||
|
||||
def __init__(self, secret_b32: str, clock=time.time):
|
||||
self.secret = secret_b32
|
||||
self.clock = clock
|
||||
self.lock = threading.Lock()
|
||||
self.used_step = None
|
||||
self.failures = deque()
|
||||
|
||||
def locked_for(self) -> int:
|
||||
now = self.clock()
|
||||
with self.lock:
|
||||
while self.failures and now - self.failures[0] > FAIL_WINDOW:
|
||||
self.failures.popleft()
|
||||
if len(self.failures) >= MAX_FAILURES:
|
||||
return int(FAIL_WINDOW - (now - self.failures[0])) + 1
|
||||
return 0
|
||||
|
||||
def check(self, code: str) -> str:
|
||||
""""ok", "locked" or "wrong"."""
|
||||
if self.locked_for():
|
||||
return "locked"
|
||||
now = self.clock()
|
||||
step = matching_step(self.secret, code, now)
|
||||
with self.lock:
|
||||
if step is not None and (self.used_step is None or step > self.used_step):
|
||||
self.used_step = step
|
||||
return "ok"
|
||||
self.failures.append(now)
|
||||
return "wrong"
|
||||
|
|
@ -7,8 +7,9 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
|
|||
~/.config/llm-host/config.json plan + settings
|
||||
~/.config/llm-host/api_key API key (0600)
|
||||
~/.local/share/llm-host/newt newt binary, after `llmhost install-newt`
|
||||
~/.config/llm-host/oidc_secret dashboard sign-in client secret (0600), after install-newt
|
||||
~/.config/llm-host/newt_secret Pangolin site secret (0600), after install-newt
|
||||
~/.config/llm-host/oidc_secret dashboard OIDC client secret (0600), after install-oidc
|
||||
~/.config/llm-host/otp_secret authenticator-app secret (0600), after install-otp
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
|
@ -26,6 +27,7 @@ CONFIG_FILE = CONFIG_DIR / "config.json"
|
|||
KEY_FILE = CONFIG_DIR / "api_key"
|
||||
OIDC_SECRET_FILE = CONFIG_DIR / "oidc_secret"
|
||||
NEWT_SECRET_FILE = CONFIG_DIR / "newt_secret"
|
||||
OTP_SECRET_FILE = CONFIG_DIR / "otp_secret"
|
||||
NEWT_DIR = DATA / "newt"
|
||||
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
|
||||
BIN_DIR = HOME / ".local/bin"
|
||||
|
|
@ -91,4 +93,4 @@ def save_secret(path, secret: str) -> None:
|
|||
|
||||
|
||||
def oidc_secret() -> str:
|
||||
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-newt")
|
||||
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-oidc")
|
||||
|
|
|
|||
254
llmhost/qr.py
Normal file
254
llmhost/qr.py
Normal file
|
|
@ -0,0 +1,254 @@
|
|||
"""A small QR code encoder, for showing an authenticator pairing link in the terminal.
|
||||
|
||||
Stdlib only, like the rest of llm-host. Byte mode, error correction level M, versions
|
||||
1-10 (up to 213 bytes, plenty for an otpauth:// URI). Follows ISO/IEC 18004, laid out
|
||||
the way Project Nayuki's reference encoder does it.
|
||||
"""
|
||||
|
||||
# Error correction level M, by version (index 0 unused).
|
||||
ECC_PER_BLOCK = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26]
|
||||
NUM_BLOCKS = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5]
|
||||
ALIGN = [[], [], [6, 18], [6, 22], [6, 26], [6, 30], [6, 34],
|
||||
[6, 22, 38], [6, 24, 42], [6, 26, 46], [6, 28, 50]]
|
||||
FORMAT_ECL_M = 0
|
||||
MAX_VERSION = 10
|
||||
|
||||
|
||||
def _raw_modules(ver):
|
||||
n = (16 * ver + 128) * ver + 64
|
||||
if ver >= 2:
|
||||
k = ver // 7 + 2
|
||||
n -= (25 * k - 10) * k - 55
|
||||
if ver >= 7:
|
||||
n -= 36
|
||||
return n
|
||||
|
||||
|
||||
def _data_codewords(ver):
|
||||
return _raw_modules(ver) // 8 - ECC_PER_BLOCK[ver] * NUM_BLOCKS[ver]
|
||||
|
||||
|
||||
def _gf_mul(x, y):
|
||||
z = 0
|
||||
for i in reversed(range(8)):
|
||||
z = (z << 1) ^ ((z >> 7) * 0x11D)
|
||||
z ^= ((y >> i) & 1) * x
|
||||
return z
|
||||
|
||||
|
||||
def _rs_divisor(degree):
|
||||
out = [0] * (degree - 1) + [1]
|
||||
root = 1
|
||||
for _ in range(degree):
|
||||
for j in range(degree):
|
||||
out[j] = _gf_mul(out[j], root)
|
||||
if j + 1 < degree:
|
||||
out[j] ^= out[j + 1]
|
||||
root = _gf_mul(root, 0x02)
|
||||
return out
|
||||
|
||||
|
||||
def _rs_remainder(data, divisor):
|
||||
out = [0] * len(divisor)
|
||||
for b in data:
|
||||
factor = b ^ out.pop(0)
|
||||
out.append(0)
|
||||
for i, coef in enumerate(divisor):
|
||||
out[i] ^= _gf_mul(coef, factor)
|
||||
return out
|
||||
|
||||
|
||||
def _codewords(data: bytes):
|
||||
for ver in range(1, MAX_VERSION + 1):
|
||||
count_bits = 8 if ver <= 9 else 16
|
||||
if 4 + count_bits + 8 * len(data) <= _data_codewords(ver) * 8:
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"too long for a QR code here ({len(data)} bytes)")
|
||||
bits = []
|
||||
def put(val, n):
|
||||
bits.extend((val >> i) & 1 for i in reversed(range(n)))
|
||||
put(0b0100, 4)
|
||||
put(len(data), count_bits)
|
||||
for b in data:
|
||||
put(b, 8)
|
||||
cap = _data_codewords(ver) * 8
|
||||
put(0, min(4, cap - len(bits)))
|
||||
put(0, -len(bits) % 8)
|
||||
pad = 0xEC
|
||||
while len(bits) < cap:
|
||||
put(pad, 8)
|
||||
pad ^= 0xEC ^ 0x11
|
||||
words = [int("".join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8)]
|
||||
|
||||
nblocks, ecl = NUM_BLOCKS[ver], ECC_PER_BLOCK[ver]
|
||||
raw = _raw_modules(ver) // 8
|
||||
nshort = nblocks - raw % nblocks
|
||||
short_len = raw // nblocks
|
||||
div = _rs_divisor(ecl)
|
||||
blocks, k = [], 0
|
||||
for i in range(nblocks):
|
||||
dlen = short_len - ecl + (0 if i < nshort else 1)
|
||||
d = words[k:k + dlen]
|
||||
k += dlen
|
||||
ecc = _rs_remainder(d, div)
|
||||
if i < nshort:
|
||||
d = d + [None]
|
||||
blocks.append(d + ecc)
|
||||
out = []
|
||||
for i in range(len(blocks[0])):
|
||||
for blk in blocks:
|
||||
if blk[i] is not None:
|
||||
out.append(blk[i])
|
||||
return ver, out
|
||||
|
||||
|
||||
class QR:
|
||||
def __init__(self, data, mask=None):
|
||||
if isinstance(data, str):
|
||||
data = data.encode("utf-8")
|
||||
self.version, words = _codewords(data)
|
||||
self.size = n = self.version * 4 + 17
|
||||
self.m = [[False] * n for _ in range(n)]
|
||||
self.fn = [[False] * n for _ in range(n)]
|
||||
self._function_patterns()
|
||||
self._place(words)
|
||||
if mask is None:
|
||||
mask = min(range(8), key=self._penalty_with)
|
||||
self.mask = mask
|
||||
self._apply_mask(mask)
|
||||
self._format_bits(mask)
|
||||
|
||||
def _set(self, x, y, dark):
|
||||
self.m[y][x] = dark
|
||||
self.fn[y][x] = True
|
||||
|
||||
def _function_patterns(self):
|
||||
n = self.size
|
||||
for i in range(n):
|
||||
self._set(6, i, i % 2 == 0)
|
||||
self._set(i, 6, i % 2 == 0)
|
||||
for cx, cy in ((3, 3), (n - 4, 3), (3, n - 4)):
|
||||
for dy in range(-4, 5):
|
||||
for dx in range(-4, 5):
|
||||
x, y = cx + dx, cy + dy
|
||||
if 0 <= x < n and 0 <= y < n:
|
||||
self._set(x, y, max(abs(dx), abs(dy)) not in (2, 4))
|
||||
pos = ALIGN[self.version]
|
||||
last = len(pos) - 1
|
||||
for i, ax in enumerate(pos):
|
||||
for j, ay in enumerate(pos):
|
||||
if (i, j) in ((0, 0), (0, last), (last, 0)):
|
||||
continue
|
||||
for dy in range(-2, 3):
|
||||
for dx in range(-2, 3):
|
||||
self._set(ax + dx, ay + dy, max(abs(dx), abs(dy)) != 1)
|
||||
self._format_bits(0) # reserve the area; redrawn after masking
|
||||
if self.version >= 7:
|
||||
rem = self.version
|
||||
for _ in range(12):
|
||||
rem = (rem << 1) ^ ((rem >> 11) * 0x1F25)
|
||||
bits = self.version << 12 | rem
|
||||
for i in range(18):
|
||||
bit = (bits >> i) & 1 == 1
|
||||
a, b = n - 11 + i % 3, i // 3
|
||||
self._set(a, b, bit)
|
||||
self._set(b, a, bit)
|
||||
|
||||
def _format_bits(self, mask):
|
||||
data = FORMAT_ECL_M << 3 | mask
|
||||
rem = data
|
||||
for _ in range(10):
|
||||
rem = (rem << 1) ^ ((rem >> 9) * 0x537)
|
||||
bits = (data << 10 | rem) ^ 0x5412
|
||||
bit = lambda i: (bits >> i) & 1 == 1
|
||||
n = self.size
|
||||
for i in range(6):
|
||||
self._set(8, i, bit(i))
|
||||
self._set(8, 7, bit(6))
|
||||
self._set(8, 8, bit(7))
|
||||
self._set(7, 8, bit(8))
|
||||
for i in range(9, 15):
|
||||
self._set(14 - i, 8, bit(i))
|
||||
for i in range(8):
|
||||
self._set(n - 1 - i, 8, bit(i))
|
||||
for i in range(8, 15):
|
||||
self._set(8, n - 15 + i, bit(i))
|
||||
self._set(8, n - 8, True)
|
||||
|
||||
def _place(self, words):
|
||||
n, i, total = self.size, 0, len(words) * 8
|
||||
right = n - 1
|
||||
while right >= 1:
|
||||
if right == 6:
|
||||
right = 5
|
||||
for vert in range(n):
|
||||
for j in range(2):
|
||||
x = right - j
|
||||
upward = ((right + 1) & 2) == 0
|
||||
y = n - 1 - vert if upward else vert
|
||||
if not self.fn[y][x] and i < total:
|
||||
self.m[y][x] = (words[i >> 3] >> (7 - (i & 7))) & 1 == 1
|
||||
i += 1
|
||||
right -= 2
|
||||
|
||||
@staticmethod
|
||||
def _mask_bit(mask, x, y):
|
||||
return [
|
||||
(x + y) % 2 == 0, y % 2 == 0, x % 3 == 0, (x + y) % 3 == 0,
|
||||
(x // 3 + y // 2) % 2 == 0, x * y % 2 + x * y % 3 == 0,
|
||||
(x * y % 2 + x * y % 3) % 2 == 0, ((x + y) % 2 + x * y % 3) % 2 == 0,
|
||||
][mask]
|
||||
|
||||
def _apply_mask(self, mask):
|
||||
for y in range(self.size):
|
||||
for x in range(self.size):
|
||||
if not self.fn[y][x] and self._mask_bit(mask, x, y):
|
||||
self.m[y][x] = not self.m[y][x]
|
||||
|
||||
def _penalty_with(self, mask):
|
||||
self._apply_mask(mask)
|
||||
self._format_bits(mask)
|
||||
p = self._penalty()
|
||||
self._apply_mask(mask) # XOR again to undo
|
||||
return p
|
||||
|
||||
def _penalty(self):
|
||||
n, m, p = self.size, self.m, 0
|
||||
lines = m + [[m[y][x] for y in range(n)] for x in range(n)]
|
||||
finder_a = [True, False, True, True, True, False, True, False, False, False, False]
|
||||
finder_b = finder_a[::-1]
|
||||
for line in lines:
|
||||
run = 1
|
||||
for i in range(1, n + 1):
|
||||
if i < n and line[i] == line[i - 1]:
|
||||
run += 1
|
||||
else:
|
||||
if run >= 5:
|
||||
p += 3 + run - 5
|
||||
run = 1
|
||||
for i in range(n - 10):
|
||||
seg = line[i:i + 11]
|
||||
if seg == finder_a or seg == finder_b:
|
||||
p += 40
|
||||
for y in range(n - 1):
|
||||
for x in range(n - 1):
|
||||
if m[y][x] == m[y][x + 1] == m[y + 1][x] == m[y + 1][x + 1]:
|
||||
p += 3
|
||||
dark = sum(sum(row) for row in m)
|
||||
p += (abs(dark * 20 - n * n * 10) // (n * n)) * 10
|
||||
return p
|
||||
|
||||
def terminal(self, quiet=2):
|
||||
"""Rows of text, two modules per character, drawn in explicit black on white so
|
||||
it scans the same on a dark or a light terminal theme."""
|
||||
n = self.size
|
||||
dark = lambda x, y: 0 <= x < n and 0 <= y < n and self.m[y][x]
|
||||
rows = []
|
||||
for y in range(-quiet, n + quiet, 2):
|
||||
line = []
|
||||
for x in range(-quiet, n + quiet):
|
||||
top, bot = dark(x, y), dark(x, y + 1)
|
||||
line.append(f"\033[{30 if top else 97};{40 if bot else 107}m▀")
|
||||
rows.append("".join(line) + "\033[0m")
|
||||
return rows
|
||||
|
|
@ -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