Compare commits
8 commits
server-sid
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e9ebeed42 | ||
|
|
c8b70afdbf | ||
|
|
e6ff4ce909 | ||
|
|
04ff14c58f | ||
|
|
6fd82448c5 | ||
|
|
e814a2359d | ||
|
|
d07a92e5b5 | ||
|
|
c8f04f49b7 |
25 changed files with 3058 additions and 130 deletions
176
README.md
176
README.md
|
|
@ -50,9 +50,14 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
|
||||||
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
|
| `llmhost switch <model>` | serve a different model (downloads it first if needed) |
|
||||||
| `llmhost download <model>` | download ahead of time |
|
| `llmhost download <model>` | download ahead of time |
|
||||||
| `llmhost watch` | download and loading progress, until the model is ready |
|
| `llmhost watch` | download and loading progress, until the model is ready |
|
||||||
| `llmhost logs -f` | follow the model server log |
|
| `llmhost logs -f` | follow the model server log (`--web` for the dashboard's, `--newt` for the tunnel's) |
|
||||||
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
|
| `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) |
|
||||||
| `llmhost key` | print the API key |
|
| `llmhost key` | print the API key |
|
||||||
|
| `llmhost install-newt` | optional: reach the API from the internet through a Pangolin tunnel; the dashboard stays local (see [Reaching it from the internet](#reaching-it-from-the-internet)) |
|
||||||
|
| `llmhost install-oidc` | optional: sign in to the dashboard through an OIDC provider instead of the API key |
|
||||||
|
| `llmhost install-otp` | optional: pair authenticator apps; their codes also open the dashboard (`--show` to add another device) |
|
||||||
|
| `llmhost expose-dashboard` | walk through publishing the dashboard through the tunnel, once it has a sign-in of its own |
|
||||||
|
| `llmhost remove-newt` / `remove-oidc` / `remove-otp` | undo the matching `install-*` |
|
||||||
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
|
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
|
||||||
| `llmhost opencode-config` | print what to add to opencode on another machine |
|
| `llmhost opencode-config` | print what to add to opencode on another machine |
|
||||||
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
|
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
|
||||||
|
|
@ -62,10 +67,136 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
|
||||||
The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization,
|
The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization,
|
||||||
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
|
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
|
||||||
|
|
||||||
|
It also lists the last 20 finished requests, each split into its two phases at the first generated token:
|
||||||
|
prompt tokens with the seconds and rate of the prefill, then generated tokens with the seconds and rate of
|
||||||
|
the generation. A request that didn't stream has no first-token mark, so its prompt seconds read `—` and its
|
||||||
|
whole duration counts as generation.
|
||||||
|
|
||||||
|
## Reaching it from the internet
|
||||||
|
|
||||||
|
A plain install is LAN-only, and the dashboard asks for the API key. Going further is a few separate,
|
||||||
|
optional steps, so the API can go online without the dashboard:
|
||||||
|
|
||||||
|
| step | what it adds |
|
||||||
|
|---|---|
|
||||||
|
| `llmhost install-newt` | the API, online through a tunnel; the dashboard stays on your LAN |
|
||||||
|
| `llmhost install-oidc` | dashboard sign-in through your OIDC provider, replacing the API key |
|
||||||
|
| `llmhost install-otp` | dashboard sign-in with codes from an authenticator app, alongside (or instead of) the key |
|
||||||
|
| `llmhost expose-dashboard` | a walkthrough for putting the dashboard online too, once it has one of those sign-ins |
|
||||||
|
|
||||||
|
### The API: `install-newt`
|
||||||
|
|
||||||
|
[newt](https://github.com/fosrl/newt) dials out to your [Pangolin](https://github.com/fosrl/pangolin) server, which
|
||||||
|
serves HTTPS on your domain. Nothing on this machine is opened to the internet, and no port is forwarded. newt runs as
|
||||||
|
a third user service, in userspace (no root). It's a pinned release, checked against its sha256 before it's installed.
|
||||||
|
|
||||||
|
Create a Newt site in Pangolin (*Sites → Add Site → Newt*, which gives an endpoint, ID and secret), then:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llmhost install-newt --api-url https://llm-api.example.com \
|
||||||
|
--endpoint https://pangolin.example.com --newt-id <site id>
|
||||||
|
```
|
||||||
|
|
||||||
|
`--api-url` is where clients will reach the API: a domain you'll add as a resource on Pangolin, not Pangolin's own
|
||||||
|
address (`--endpoint`). It's asked for first, because llm-host uses it to describe the resource and to print the
|
||||||
|
right `opencode-install.sh` command everywhere it gives one.
|
||||||
|
|
||||||
|
It asks for the site secret, or reads `$LLMHOST_NEWT_SECRET`; it's never taken as a flag, so it stays out of shell
|
||||||
|
history. The secret is stored in `~/.config/llm-host/newt_secret` (mode 600) and handed to newt in its environment
|
||||||
|
at start, never written into a service file or `config.json`. Running it again changes only what you give it.
|
||||||
|
|
||||||
|
Then add one HTTP resource in Pangolin, for the API: the `--api-url` host → `<this machine's LAN IP>:<API port>`,
|
||||||
|
with Pangolin's own authentication off, since llm-host checks the API key. Point it at the LAN IP, not
|
||||||
|
`localhost`, which llm-host treats as local. Clients use `https://<API host>/v1` with the key; for opencode, see
|
||||||
|
[`opencode-install.sh`](#connecting-opencode).
|
||||||
|
|
||||||
|
### Dashboard sign-in: `install-oidc` and `install-otp`
|
||||||
|
|
||||||
|
Out of the box the dashboard takes the API key, the same key you hand to API users. That's fine on your LAN, but
|
||||||
|
anyone holding the key could also stop, start or switch the model from the dashboard. Before the dashboard goes
|
||||||
|
online, give it a sign-in of its own.
|
||||||
|
|
||||||
|
**OIDC** (`llmhost install-oidc`) replaces the key with sign-in through your identity provider, limited to the
|
||||||
|
groups or usernames you allow. Register a confidential client using `client_secret_basic`, the authorization-code
|
||||||
|
flow with PKCE (S256), scopes `openid profile email groups`, and the redirect URI `https://<dashboard host>/auth/callback`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
llmhost install-oidc --public-url https://llm-dash.example.com \
|
||||||
|
--issuer https://auth.example.com --client-id <client id from the provider> \
|
||||||
|
--allow-group llm-admins # and/or --allow-user <username>; repeatable
|
||||||
|
```
|
||||||
|
|
||||||
|
It asks for the client secret (or reads `$LLMHOST_OIDC_SECRET`) and checks the provider's discovery document.
|
||||||
|
Sign-in happens at the public URL, and visits by any other address are sent there, so the dashboard must be
|
||||||
|
reachable at that URL; see `expose-dashboard`. For Authelia, the client looks like this:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
identity_providers:
|
||||||
|
oidc:
|
||||||
|
clients:
|
||||||
|
- client_id: llm-host
|
||||||
|
client_name: llm-host dashboard
|
||||||
|
client_secret: '$pbkdf2-sha512$...' # authelia crypto hash generate pbkdf2 --random
|
||||||
|
public: false
|
||||||
|
authorization_policy: two_factor
|
||||||
|
require_pkce: true
|
||||||
|
pkce_challenge_method: S256
|
||||||
|
redirect_uris: ['https://llm-dash.example.com/auth/callback']
|
||||||
|
scopes: [openid, profile, email, groups]
|
||||||
|
response_types: [code]
|
||||||
|
grant_types: [authorization_code]
|
||||||
|
token_endpoint_auth_method: client_secret_basic
|
||||||
|
```
|
||||||
|
|
||||||
|
How OIDC sign-in behaves:
|
||||||
|
|
||||||
|
- **Only listed people get in.** A person must be in an allowed group or have an allowed username
|
||||||
|
(`preferred_username`, falling back to email). Groups come from userinfo.
|
||||||
|
- **The ID token is checked.** Its issuer, audience, expiry and nonce must match. It arrives directly from the
|
||||||
|
token endpoint over TLS, which OIDC allows in place of verifying its signature.
|
||||||
|
|
||||||
|
**Authenticator codes** (`llmhost install-otp`) need no provider. It shows a QR code in the terminal; scan it with
|
||||||
|
any authenticator app, then type the code it shows to confirm. After that, the dashboard's sign-in also accepts a
|
||||||
|
current 6-digit code. To add another phone later, `llmhost install-otp --show` shows the same pairing again. Each
|
||||||
|
code works once, and after 5 wrong codes in 5 minutes codes are refused for a while. The limit is global, because
|
||||||
|
behind a tunnel every request comes from the same address. Codes are TOTP: SHA-1, 6 digits, 30 seconds, the
|
||||||
|
defaults every app supports. The secret is kept in `~/.config/llm-host/otp_secret` (mode 600). The API key keeps
|
||||||
|
working on the dashboard too, until `expose-dashboard` offers to turn it off there.
|
||||||
|
|
||||||
|
For both, sessions are HttpOnly, `SameSite=Lax` cookies, Secure behind HTTPS. They last 12 hours and are held in
|
||||||
|
memory, so restarting the dashboard signs everyone out. State-changing requests must come from the dashboard's own
|
||||||
|
page. While OIDC is on, it's the only way in, and codes come back with `remove-oidc`.
|
||||||
|
|
||||||
|
### The dashboard: `expose-dashboard`
|
||||||
|
|
||||||
|
`llmhost expose-dashboard` won't start until `install-newt` is done. It then checks the dashboard's sign-in:
|
||||||
|
|
||||||
|
- **OIDC:** fine.
|
||||||
|
- **Authenticator codes:** it offers to stop the API key opening the dashboard.
|
||||||
|
- **The key alone:** it explains the risk and asks before going on (`--force` skips the question).
|
||||||
|
|
||||||
|
Then it describes the Pangolin resource to add (the dashboard's host → `<LAN IP>:<dashboard port>`) and, once you
|
||||||
|
press Enter, checks the public URL reaches this dashboard. It records only that the dashboard is public, not where.
|
||||||
|
|
||||||
|
### Which address clients are given
|
||||||
|
|
||||||
|
Setup's closing message, `llmhost opencode-config` and the dashboard's **Connect** dialog all print the
|
||||||
|
`opencode-install.sh` command, for these addresses:
|
||||||
|
|
||||||
|
| state | commands shown |
|
||||||
|
|---|---|
|
||||||
|
| no tunnel | the local network (`http://<host>.local:<API port>`) |
|
||||||
|
| `install-newt` done, dashboard local | the internet (`--api-url`), then the local network |
|
||||||
|
| `expose-dashboard` done | the internet only, since the dashboard is then seen from outside |
|
||||||
|
|
||||||
|
`llmhost status` shows the tunnel and sign-in settings. `setup` and `update` keep them, and `update` moves newt to
|
||||||
|
a newly pinned release. Each step has an undo: `remove-newt`, `remove-oidc`, `remove-otp`.
|
||||||
|
|
||||||
## Connecting opencode
|
## Connecting opencode
|
||||||
|
|
||||||
**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official
|
**On the server itself**, setup handles it: if opencode isn't installed it offers to install it, through
|
||||||
installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json`
|
`opencode-install.sh --install-only` like any other machine (which runs opencode's official installer, into
|
||||||
|
`~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json`
|
||||||
pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. It shows up
|
pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. It shows up
|
||||||
in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs
|
in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs
|
||||||
the file up as `opencode.json.before-llmhost`.
|
the file up as `opencode.json.before-llmhost`.
|
||||||
|
|
@ -73,10 +204,28 @@ the file up as `opencode.json.before-llmhost`.
|
||||||
(`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`.
|
(`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`.
|
||||||
A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead.
|
A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead.
|
||||||
|
|
||||||
**On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner
|
**On another machine**, use `opencode-install.sh` (below); setup ends by printing the exact command for this
|
||||||
that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (popos.local)`
|
server. To do it by hand instead, run `llmhost opencode-config` on the server. It prints a provider block and a
|
||||||
|
one-liner that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (mybox.local)`
|
||||||
— under the provider id `llmhost-<shorthost>`.
|
— under the provider id `llmhost-<shorthost>`.
|
||||||
|
|
||||||
|
**On any machine, in one step**, run `opencode-install.sh` from this repo. It needs only the API's address and
|
||||||
|
the key, not the dashboard or llm-host, so you can hand it to people who reach just the API, such as through a
|
||||||
|
tunnel that exposes the API alone. The dashboard's **Connect** button shows the command with the address filled in:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
/bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/opencode-install.sh)" -- --url https://<API host>
|
||||||
|
```
|
||||||
|
|
||||||
|
It checks the server answers with the key, which it asks for without echoing it (or pass `--key` /
|
||||||
|
`$LLMHOST_API_KEY`, at the cost of the key landing in shell history). Then it installs opencode with the official
|
||||||
|
installer, unless it's already there, saves the key to `~/.config/opencode/llmhost-<host>.key` (mode 600), and adds
|
||||||
|
the provider to `opencode.json`. Everything else in that file is kept, and it's backed up as
|
||||||
|
`opencode.json.before-llmhost` first. It makes the server the default model when you have none; if you do, it asks
|
||||||
|
first, and `--default` / `--no-default` decide without asking. It also drops any key opencode had cached for that
|
||||||
|
provider. A `.jsonc` config is never rewritten; the block is printed to paste instead. `--remove` takes the server
|
||||||
|
back out. It needs `curl` and `python3`.
|
||||||
|
|
||||||
### One opencode, several servers
|
### One opencode, several servers
|
||||||
|
|
||||||
The two paths use different provider ids, so a single opencode config can point at a local server and any number
|
The two paths use different provider ids, so a single opencode config can point at a local server and any number
|
||||||
|
|
@ -109,8 +258,8 @@ never overwritten (setup takes `llmhost-local` instead and says so), and `uninst
|
||||||
provider — remote ones, and providers llm-host didn't create, are left in place. If a provider's default model
|
provider — remote ones, and providers llm-host didn't create, are left in place. If a provider's default model
|
||||||
goes away with it, `model` is repointed at a surviving llm-host provider, and dropped only if there is none.
|
goes away with it, `model` is repointed at a surviving llm-host provider, and dropped only if there is none.
|
||||||
|
|
||||||
Retiring a server is the one thing the servers can't do for each other: uninstalling on `popos` can't reach the
|
Retiring a server is the one thing the servers can't do for each other: uninstalling on `mybox` can't reach the
|
||||||
clients pointing at it. On each client, run `llmhost opencode-remove --host popos.local` (or delete the block by
|
clients pointing at it. On each client, run `llmhost opencode-remove --host mybox.local` (or delete the block by
|
||||||
hand if llm-host isn't installed there).
|
hand if llm-host isn't installed there).
|
||||||
|
|
||||||
### If opencode keeps asking for the API key
|
### If opencode keeps asking for the API key
|
||||||
|
|
@ -199,6 +348,10 @@ python3 tests/test_opencode.py # or run one directly
|
||||||
| `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache |
|
| `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache |
|
||||||
| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server |
|
| `tests/test_proxy.py` | model names, dropping client reasoning settings, upstream key, streamed-run counting, against a fake server |
|
||||||
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
|
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
|
||||||
|
| `tests/test_dashboard_auth.py` | API-key mode, and OIDC sign-in against a fake provider: PKCE, state/nonce/aud/iss/exp checks, allow list, origin check, sign-out |
|
||||||
|
| `tests/test_opencode_install.py` | `opencode-install.sh` against a fake API in a throwaway HOME: new and existing configs, default-model choice, cached-key cleanup, `--remove`, refusals |
|
||||||
|
| `tests/test_newt.py` | `install-newt`, `install-oidc`, `install-otp`, `expose-dashboard` and their undos against fake services: pinned checksum, secrets kept out of config, output and argv, re-runs |
|
||||||
|
| `tests/test_otp.py` | TOTP against RFC 6238, code replay and lockout, the QR encoder against reference matrices, code sign-in on the dashboard |
|
||||||
| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update |
|
| `tests/test_reasoning.py` | effort options matching the real chat templates; the setting surviving an update |
|
||||||
|
|
||||||
## Continuing on an NVIDIA box
|
## Continuing on an NVIDIA box
|
||||||
|
|
@ -243,6 +396,10 @@ suites are hermetic and don't need a GPU), so run that first.
|
||||||
| `~/.local/share/llm-host/` | this repo (`src/`), backend venvs, the assembled CUDA toolkit |
|
| `~/.local/share/llm-host/` | this repo (`src/`), backend venvs, the assembled CUDA toolkit |
|
||||||
| `~/.config/llm-host/config.json` | the plan: backend, fitting models, active model, ports |
|
| `~/.config/llm-host/config.json` | the plan: backend, fitting models, active model, ports |
|
||||||
| `~/.config/llm-host/api_key` | API key (mode 600) |
|
| `~/.config/llm-host/api_key` | API key (mode 600) |
|
||||||
|
| `~/.config/llm-host/oidc_secret` | OIDC client secret (mode 600), after `install-oidc` |
|
||||||
|
| `~/.config/llm-host/otp_secret` | authenticator-app secret (mode 600), after `install-otp` |
|
||||||
|
| `~/.config/llm-host/newt_secret` | Pangolin site secret (mode 600), after `install-newt` |
|
||||||
|
| `~/.local/share/llm-host/newt/` | the newt binary, after `install-newt` |
|
||||||
| `~/.cache/huggingface/hub/` | downloaded models |
|
| `~/.cache/huggingface/hub/` | downloaded models |
|
||||||
| Linux: `~/.config/systemd/user/llm-host-{model,web}.service` | services (`journalctl --user -u llm-host-model`) |
|
| Linux: `~/.config/systemd/user/llm-host-{model,web}.service` | services (`journalctl --user -u llm-host-model`) |
|
||||||
| macOS: `~/Library/LaunchAgents/dev.llm-host.{model,web}.plist` | services; logs in `~/Library/Logs/llm-host/` |
|
| macOS: `~/Library/LaunchAgents/dev.llm-host.{model,web}.plist` | services; logs in `~/Library/Logs/llm-host/` |
|
||||||
|
|
@ -257,4 +414,7 @@ On macOS the services are launchd agents, so they run while you're logged in.
|
||||||
`reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's
|
`reasoning_effort` (top-level or in `chat_template_kwargs`) is dropped and the dashboard's
|
||||||
setting applied instead.
|
setting applied instead.
|
||||||
- AMD (ROCm), Intel and CPU-only machines aren't supported yet.
|
- AMD (ROCm), Intel and CPU-only machines aren't supported yet.
|
||||||
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't expose them to the internet.
|
- The API and dashboard use plain HTTP and are meant for a trusted LAN. Don't forward their ports to the internet;
|
||||||
|
use [`llmhost install-newt`](#reaching-it-from-the-internet), which puts HTTPS in front, and give the dashboard
|
||||||
|
its own sign-in before `expose-dashboard`.
|
||||||
|
- Everyone using the API shares one key, with no per-person revocation or rate limits.
|
||||||
|
|
|
||||||
|
|
@ -104,7 +104,8 @@ def run_server(cfg, entry, choice, args):
|
||||||
controls = hfcache.template_controls(choice["repo"])
|
controls = hfcache.template_controls(choice["repo"])
|
||||||
srv = proxy.listen(port, proxy.make_handler(
|
srv = proxy.listen(port, proxy.make_handler(
|
||||||
inner, entry["name"], choice.get("est_context", entry["context"]), paths.api_key(), stats,
|
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")
|
proxy.kill_stale(inner, VENV, "mlx_lm")
|
||||||
|
|
||||||
exe = str(VENV / "bin/mlx_lm.server")
|
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,
|
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
|
"""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
|
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
|
# 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).
|
# 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)}
|
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
|
return
|
||||||
if self.path.startswith("/v1/models"):
|
if self.path.startswith("/v1/models"):
|
||||||
return self._json(200, {"object": "list", "data": [
|
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)
|
self._forward("GET", None)
|
||||||
|
|
||||||
def _model_ok(self, body):
|
def _model_ok(self, body):
|
||||||
|
|
|
||||||
|
|
@ -175,7 +175,8 @@ def run_server(cfg, entry, choice, args):
|
||||||
srv = proxy.listen(port, proxy.make_handler(
|
srv = proxy.listen(port, proxy.make_handler(
|
||||||
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
|
inner, entry["name"], choice.get("est_context", entry["context"]), key, stats,
|
||||||
aliases=(choice.get("repo"),), reasoning=proxy.reasoning_setting(entry, controls),
|
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")
|
proxy.kill_stale(inner, VENV, "vllm")
|
||||||
exe = str(VENV / "bin/vllm")
|
exe = str(VENV / "bin/vllm")
|
||||||
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.
|
# vLLM's output goes straight to ours (the service log); nothing in it needs reading.
|
||||||
|
|
|
||||||
399
llmhost/cli.py
399
llmhost/cli.py
|
|
@ -8,6 +8,7 @@ import subprocess
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
from . import hfcache, hw, opencode, paths, plan, service
|
from . import hfcache, hw, opencode, paths, plan, service
|
||||||
|
|
@ -117,7 +118,11 @@ def carried_settings(old, names):
|
||||||
`llmhost update` would quietly put every model back to "Model default". Models that no
|
`llmhost update` would quietly put every model back to "Model default". Models that no
|
||||||
longer fit lose their setting along with their plan."""
|
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}
|
kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names}
|
||||||
return {"reasoning": kept} if kept else {}
|
out = {"reasoning": kept} if kept else {}
|
||||||
|
for k in ("newt", "dashboard_auth", "dashboard_key_login", "dashboard_public"): # set by install-*/expose-dashboard
|
||||||
|
if old.get(k) is not None: # dashboard_key_login is False when it matters
|
||||||
|
out[k] = old[k]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def cmd_setup(a):
|
def cmd_setup(a):
|
||||||
|
|
@ -190,6 +195,10 @@ def cmd_setup(a):
|
||||||
if not a.no_start:
|
if not a.no_start:
|
||||||
service.restart("web")
|
service.restart("web")
|
||||||
service.restart("model")
|
service.restart("model")
|
||||||
|
if cfg.get("newt") and service.installed("newt"):
|
||||||
|
from . import newt
|
||||||
|
if newt.ensure_binary(say):
|
||||||
|
service.restart("newt")
|
||||||
host = default_host()
|
host = default_host()
|
||||||
say(f"""
|
say(f"""
|
||||||
Done.
|
Done.
|
||||||
|
|
@ -199,7 +208,11 @@ Done.
|
||||||
Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch progress with: llmhost watch"}""")
|
Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch progress with: llmhost watch"}""")
|
||||||
if not a.no_opencode:
|
if not a.no_opencode:
|
||||||
setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode)
|
setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode)
|
||||||
say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.")
|
say("\nOther machines: connect their opencode to this server with one line there. It installs\n"
|
||||||
|
"opencode if needed, asks for the API key (show it here with `llmhost key`), and adds the\n"
|
||||||
|
"server to opencode.json.")
|
||||||
|
for where, url in opencode.client_targets(cfg, host):
|
||||||
|
say(f" {where}:\n {opencode.remote_command(url)}")
|
||||||
if os.environ.get("LLMHOST_PATH_NOTE"):
|
if os.environ.get("LLMHOST_PATH_NOTE"):
|
||||||
say("\n" + os.environ["LLMHOST_PATH_NOTE"])
|
say("\n" + os.environ["LLMHOST_PATH_NOTE"])
|
||||||
|
|
||||||
|
|
@ -328,7 +341,7 @@ def _service_check():
|
||||||
def cmd_status(a):
|
def cmd_status(a):
|
||||||
cfg = _service_check()
|
cfg = _service_check()
|
||||||
host = default_host()
|
host = default_host()
|
||||||
for name in service.NAMES:
|
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
|
||||||
st, up = service.state(name)
|
st, up = service.state(name)
|
||||||
upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else ""
|
upt = f" (up {int(up // 3600)}h{int(up % 3600 // 60):02d}m)" if up else ""
|
||||||
say(f"{name:6} {st}{upt}")
|
say(f"{name:6} {st}{upt}")
|
||||||
|
|
@ -340,6 +353,18 @@ def cmd_status(a):
|
||||||
except Exception:
|
except Exception:
|
||||||
say(f"active model {cfg['active']} is not answering yet")
|
say(f"active model {cfg['active']} is not answering yet")
|
||||||
say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}")
|
say(f"api http://{host}:{cfg['api_port']}/v1\ndashboard http://{host}:{cfg['web_port']}")
|
||||||
|
d = cfg.get("dashboard_auth") or {}
|
||||||
|
if d.get("mode") == "oidc":
|
||||||
|
who = ", ".join([f"group {g}" for g in d.get("allowed_groups", [])] + [f"user {u}" for u in d.get("allowed_users", [])])
|
||||||
|
say(f"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"):
|
||||||
|
api = cfg["newt"].get("api_url")
|
||||||
|
say(f"tunnel newt -> {cfg['newt']['endpoint']}" + (f"; API at {api}/v1" if api else ""))
|
||||||
|
say(f"dashboard {'public (expose-dashboard)' if cfg.get('dashboard_public') else 'local network only'}")
|
||||||
|
|
||||||
|
|
||||||
def cmd_models(a):
|
def cmd_models(a):
|
||||||
|
|
@ -375,9 +400,10 @@ def cmd_ctl(a):
|
||||||
|
|
||||||
def cmd_logs(a):
|
def cmd_logs(a):
|
||||||
_service_check()
|
_service_check()
|
||||||
|
name = "newt" if a.newt else "web" if a.web else "model"
|
||||||
if a.follow:
|
if a.follow:
|
||||||
os.execvp(service.log_command("model")[0], service.log_command("model"))
|
os.execvp(service.log_command(name)[0], service.log_command(name))
|
||||||
for line in service.logs("web" if a.web else "model", a.n):
|
for line in service.logs(name, a.n):
|
||||||
say(line)
|
say(line)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -466,6 +492,310 @@ def cmd_key(a):
|
||||||
say(paths.api_key())
|
say(paths.api_key())
|
||||||
|
|
||||||
|
|
||||||
|
def _restart_if_running(name):
|
||||||
|
if service.state(name)[0] in ("active", "activating"):
|
||||||
|
if not service.restart(name):
|
||||||
|
say(f"Couldn't restart the {name} service; see `llmhost logs --{name}`.")
|
||||||
|
|
||||||
|
|
||||||
|
def lan_ip():
|
||||||
|
"""This machine's address on its default route -- what newt, running here, should dial
|
||||||
|
to reach the services. Connecting a UDP socket sends nothing."""
|
||||||
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
try:
|
||||||
|
s.connect(("192.0.2.1", 9)) # TEST-NET-1: never routed anywhere
|
||||||
|
return s.getsockname()[0]
|
||||||
|
except OSError:
|
||||||
|
return "127.0.0.1"
|
||||||
|
finally:
|
||||||
|
s.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _ask(label, given, default=None, flag=None, secret=False, env=None):
|
||||||
|
"""A value from its flag, its env var, or a prompt (keeping `default` on Enter).
|
||||||
|
Without a terminal, a value that's still missing is an error naming the flag."""
|
||||||
|
if given:
|
||||||
|
return given
|
||||||
|
if env and os.environ.get(env):
|
||||||
|
return os.environ[env]
|
||||||
|
if not sys.stdin.isatty():
|
||||||
|
if default:
|
||||||
|
return default
|
||||||
|
sys.exit(f"missing {flag or ('$' + env)}" + (f" (or ${env})" if flag and env else ""))
|
||||||
|
hint = " [keep current]" if secret and default else (f" [{default}]" if default else "")
|
||||||
|
if secret:
|
||||||
|
import getpass
|
||||||
|
v = getpass.getpass(f"{label}{hint}: ").strip()
|
||||||
|
else:
|
||||||
|
v = input(f"{label}{hint}: ").strip()
|
||||||
|
v = v or default
|
||||||
|
if not v:
|
||||||
|
sys.exit(f"{label} is required")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
def _check_url(label, url, bare=True):
|
||||||
|
import urllib.parse
|
||||||
|
u = urllib.parse.urlsplit(url)
|
||||||
|
if u.scheme not in ("http", "https") or not u.netloc or (bare and u.path.strip("/")):
|
||||||
|
sys.exit(f"{label} should look like https://host.example.com, not {url!r}")
|
||||||
|
if u.scheme != "https":
|
||||||
|
sys.exit(f"{label} must be https:// -- this is the address people reach from the internet")
|
||||||
|
return url.rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_install_newt(a):
|
||||||
|
"""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
|
||||||
|
cfg = _service_check()
|
||||||
|
old_n = cfg.get("newt") or {}
|
||||||
|
newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for
|
||||||
|
|
||||||
|
api_url = _ask("The API's public URL, as clients will reach it (e.g. https://llm-api.example.com)",
|
||||||
|
a.api_url, old_n.get("api_url"), "--api-url").strip().rstrip("/")
|
||||||
|
api_url = _check_url("API URL", api_url[:-3] if api_url.endswith("/v1") else api_url)
|
||||||
|
|
||||||
|
say("\nPangolin site (Pangolin: Sites -> Add Site -> Newt):")
|
||||||
|
endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint (your Pangolin server, not the API's URL)",
|
||||||
|
a.endpoint, old_n.get("endpoint"), "--endpoint"))
|
||||||
|
if urllib.parse.urlsplit(endpoint).netloc == urllib.parse.urlsplit(api_url).netloc:
|
||||||
|
sys.exit("The Pangolin endpoint is the Pangolin server itself; the API's URL is a resource on it, "
|
||||||
|
"so the two can't be the same.")
|
||||||
|
site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id")
|
||||||
|
have_secret = paths.NEWT_SECRET_FILE.exists() and old_n
|
||||||
|
newt_secret = _ask(" Newt secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_NEWT_SECRET")
|
||||||
|
|
||||||
|
newt.ensure_binary(say)
|
||||||
|
if newt_secret != "keep":
|
||||||
|
paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret)
|
||||||
|
cfg["newt"] = {"endpoint": endpoint, "id": site_id, "api_url": api_url}
|
||||||
|
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:
|
||||||
|
{urllib.parse.urlsplit(api_url).netloc} -> http://{ip}:{cfg['api_port']}
|
||||||
|
with Pangolin's own authentication off (llm-host checks the API key). Point it at {ip}, not
|
||||||
|
localhost: requests from localhost count as local here.
|
||||||
|
|
||||||
|
Clients then use {api_url}/v1 with the API key. To connect opencode on another machine, run
|
||||||
|
this there (it asks for the key, which `llmhost key` shows):
|
||||||
|
{opencode.remote_command(api_url)}
|
||||||
|
|
||||||
|
The dashboard stays on your local network. To put it online too, first give it a sign-in
|
||||||
|
that isn't the API key you hand out (`llmhost install-oidc` or `llmhost install-otp`), then
|
||||||
|
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))
|
||||||
|
cfg.pop("dashboard_public", None) # nothing is public without the tunnel
|
||||||
|
paths.save_config(cfg)
|
||||||
|
say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.")
|
||||||
|
|
||||||
|
|
||||||
|
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 (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.
|
||||||
|
groups, users = old_d.get("allowed_groups", []), old_d.get("allowed_users", [])
|
||||||
|
if not (groups or users):
|
||||||
|
groups = [g.strip() for g in _ask(" Groups allowed in (comma-separated)", None, None,
|
||||||
|
"--allow-group").split(",") if g.strip()]
|
||||||
|
if not (groups or users):
|
||||||
|
sys.exit("say who may sign in: --allow-group <group> and/or --allow-user <username>")
|
||||||
|
|
||||||
|
dash = {"mode": "oidc", "issuer": issuer, "client_id": client_id, "public_url": public_url,
|
||||||
|
"allowed_groups": sorted(set(groups)), "allowed_users": sorted(set(users))}
|
||||||
|
try:
|
||||||
|
oidc.OIDC(dash, paths.oidc_secret() if secret == "keep" else secret).discovery()
|
||||||
|
except oidc.AuthError as e:
|
||||||
|
sys.exit(str(e))
|
||||||
|
if secret != "keep":
|
||||||
|
paths.save_secret(paths.OIDC_SECRET_FILE, secret)
|
||||||
|
cfg["dashboard_auth"] = dash
|
||||||
|
paths.save_config(cfg)
|
||||||
|
_restart_if_running("web")
|
||||||
|
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. 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
|
||||||
|
|
||||||
|
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_oidc(a):
|
||||||
|
cfg = _service_check()
|
||||||
|
had = bool(cfg.pop("dashboard_auth", None))
|
||||||
|
paths.OIDC_SECRET_FILE.unlink(missing_ok=True)
|
||||||
|
paths.save_config(cfg)
|
||||||
|
_restart_if_running("web")
|
||||||
|
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")
|
||||||
|
# Only that it's public, not where: what's handed to clients is the API's address, and
|
||||||
|
# a public dashboard is seen from outside, so it stops offering the LAN one.
|
||||||
|
cfg["dashboard_public"] = True
|
||||||
|
paths.save_config(cfg)
|
||||||
|
if not sys.stdin.isatty():
|
||||||
|
return
|
||||||
|
input("\nPress Enter once the resource is saved, to check it from here... ")
|
||||||
|
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):
|
def cmd_download(a):
|
||||||
cfg = _service_check()
|
cfg = _service_check()
|
||||||
m = next((x for x in cfg["models"] if x["name"] == a.model), None)
|
m = next((x for x in cfg["models"] if x["name"] == a.model), None)
|
||||||
|
|
@ -478,24 +808,32 @@ def cmd_download(a):
|
||||||
|
|
||||||
def cmd_opencode(a):
|
def cmd_opencode(a):
|
||||||
cfg = _service_check()
|
cfg = _service_check()
|
||||||
host = a.host or default_host()
|
if a.host: # an address given explicitly: that one, as before
|
||||||
|
targets = [("", f"http://{a.host}:{cfg['api_port']}")]
|
||||||
|
else:
|
||||||
|
targets = opencode.client_targets(cfg, default_host())
|
||||||
|
base = targets[0][1]
|
||||||
|
host = urllib.parse.urlsplit(base).hostname
|
||||||
prov = a.provider or opencode.remote_provider(host)
|
prov = a.provider or opencode.remote_provider(host)
|
||||||
keyfile = opencode.remote_key_file(prov)
|
keyfile = opencode.remote_key_file(prov)
|
||||||
snippet = {
|
snippet = {
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host)},
|
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host, base_url=base + "/v1")},
|
||||||
"model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry
|
"model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry
|
||||||
}
|
}
|
||||||
if a.json:
|
if a.json:
|
||||||
say(json.dumps(snippet, indent=2))
|
say(json.dumps(snippet, indent=2))
|
||||||
return
|
return
|
||||||
say(f"""(On this machine itself, `llmhost opencode-setup` does all of this automatically.)
|
say("(On this machine itself, `llmhost opencode-setup` does all of this automatically.)\n\n"
|
||||||
|
"On another machine, run this there. It installs opencode if needed, asks for the API key\n"
|
||||||
|
"(`llmhost key` shows it here), and adds this server to opencode.json:")
|
||||||
|
for where, url in targets:
|
||||||
|
say(f" {where}:\n {opencode.remote_command(url)}" if where else f" {opencode.remote_command(url)}")
|
||||||
|
say(f"""
|
||||||
|
Or by hand, for {base}/v1:
|
||||||
|
|
||||||
On another machine running opencode:
|
1. Save the API key: paste the output of `llmhost key` into {keyfile} (mode 600), or
|
||||||
|
mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{default_host()} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile}
|
||||||
1. Save the API key:
|
|
||||||
mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile}
|
|
||||||
(or paste the output of `llmhost key` into {keyfile})
|
|
||||||
|
|
||||||
2. Merge this into ~/.config/opencode/opencode.json:
|
2. Merge this into ~/.config/opencode/opencode.json:
|
||||||
""")
|
""")
|
||||||
|
|
@ -554,7 +892,7 @@ def cmd_uninstall(a):
|
||||||
# Read the catalog now: --purge deletes it along with the rest of llm-host.
|
# Read the catalog now: --purge deletes it along with the rest of llm-host.
|
||||||
cached = cached_catalog_models()
|
cached = cached_catalog_models()
|
||||||
cfg = paths.load_config() or {}
|
cfg = paths.load_config() or {}
|
||||||
for name in service.NAMES:
|
for name in service.NAMES + tuple(n for n in service.OPTIONAL if service.installed(n)):
|
||||||
service.uninstall(name)
|
service.uninstall(name)
|
||||||
# Stopping returns before the processes have exited (launchd especially). Wait, so a
|
# Stopping returns before the processes have exited (launchd especially). Wait, so a
|
||||||
# reinstall right after this finds the ports free instead of moving to other ones.
|
# reinstall right after this finds the ports free instead of moving to other ones.
|
||||||
|
|
@ -563,7 +901,7 @@ def cmd_uninstall(a):
|
||||||
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
|
ours = list(range(cfg["api_port"], cfg["api_port"] + span)) + ([cfg["web_port"]] if cfg.get("web_port") else [])
|
||||||
with Spinner("Waiting for the services to exit"):
|
with Spinner("Waiting for the services to exit"):
|
||||||
wait_ports_free(ours, timeout=30)
|
wait_ports_free(ours, timeout=30)
|
||||||
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
|
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test", "newt"):
|
||||||
shutil.rmtree(paths.DATA / d, ignore_errors=True)
|
shutil.rmtree(paths.DATA / d, ignore_errors=True)
|
||||||
say("Removed services and backend environments.")
|
say("Removed services and backend environments.")
|
||||||
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
|
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
|
||||||
|
|
@ -637,6 +975,11 @@ def cmd_run_model(a):
|
||||||
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
|
mlx.run_server(cfg, entry, choice, plan.mlx_args(entry, choice, cfg["api_port"] + 1))
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_run_newt(a):
|
||||||
|
from . import newt
|
||||||
|
newt.run()
|
||||||
|
|
||||||
|
|
||||||
def cmd_run_web(a):
|
def cmd_run_web(a):
|
||||||
_service_check()
|
_service_check()
|
||||||
service.trim_log("web")
|
service.trim_log("web")
|
||||||
|
|
@ -679,10 +1022,35 @@ def main(argv=None):
|
||||||
s.add_argument("-f", "--follow", action="store_true")
|
s.add_argument("-f", "--follow", action="store_true")
|
||||||
s.add_argument("-n", type=int, default=100)
|
s.add_argument("-n", type=int, default=100)
|
||||||
s.add_argument("--web", action="store_true", help="dashboard logs instead")
|
s.add_argument("--web", action="store_true", help="dashboard logs instead")
|
||||||
|
s.add_argument("--newt", action="store_true", help="tunnel logs instead")
|
||||||
s.set_defaults(fn=cmd_logs)
|
s.set_defaults(fn=cmd_logs)
|
||||||
sub.add_parser("watch", help="show download and loading progress until the model is ready"
|
sub.add_parser("watch", help="show download and loading progress until the model is ready"
|
||||||
).set_defaults(fn=cmd_watch)
|
).set_defaults(fn=cmd_watch)
|
||||||
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key)
|
||||||
|
s = sub.add_parser("install-newt", help="reach the API from the internet through a Pangolin tunnel (dashboard stays local)")
|
||||||
|
s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com")
|
||||||
|
s.add_argument("--api-url", help="the API's public address, e.g. https://llm-api.example.com (a resource on Pangolin)")
|
||||||
|
s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)")
|
||||||
|
s.set_defaults(fn=cmd_install_newt)
|
||||||
|
sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt)
|
||||||
|
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 = sub.add_parser("download", help="download a model ahead of time")
|
||||||
s.add_argument("model")
|
s.add_argument("model")
|
||||||
s.set_defaults(fn=cmd_download)
|
s.set_defaults(fn=cmd_download)
|
||||||
|
|
@ -710,6 +1078,7 @@ def main(argv=None):
|
||||||
s.set_defaults(fn=cmd_uninstall)
|
s.set_defaults(fn=cmd_uninstall)
|
||||||
sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
|
sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
|
||||||
sub.add_parser("run-web").set_defaults(fn=cmd_run_web)
|
sub.add_parser("run-web").set_defaults(fn=cmd_run_web)
|
||||||
|
sub.add_parser("run-newt").set_defaults(fn=cmd_run_newt)
|
||||||
|
|
||||||
a = ap.parse_args(argv)
|
a = ap.parse_args(argv)
|
||||||
a.fn(a)
|
a.fn(a)
|
||||||
|
|
|
||||||
89
llmhost/newt.py
Normal file
89
llmhost/newt.py
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
"""Optional internet access through a Pangolin tunnel (newt). Stdlib only.
|
||||||
|
|
||||||
|
`llmhost install-newt` is the upgrade path from a LAN install. It
|
||||||
|
- downloads a pinned newt release and checks it against the sha256 below,
|
||||||
|
- runs it as a third user service ("newt", via `llmhost run-newt`), which dials out to
|
||||||
|
the Pangolin server -- nothing on this machine is opened to the internet,
|
||||||
|
- and switches the dashboard to OIDC sign-in (web/oidc.py), because once it's public the
|
||||||
|
API key is too much power to hand out: it also stops and switches the model.
|
||||||
|
|
||||||
|
newt runs in userspace (no root, no kernel WireGuard). Its site secret is kept in
|
||||||
|
~/.config/llm-host/newt_secret (0600) and handed over in its environment at start, never
|
||||||
|
written into the service file.
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
import tempfile
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from . import paths
|
||||||
|
|
||||||
|
VERSION = "1.19.0"
|
||||||
|
# From the GitHub release's asset digests for VERSION.
|
||||||
|
SHA256 = {
|
||||||
|
"linux_amd64": "6d40e223fa49d8bcfa9b7094208c58ff616997979bff7c884d0af61fcc1c5376",
|
||||||
|
"linux_arm64": "2a282e3edda7be17f092ac58aff0ec6dac9ddd152a642e8e61e6d625f2abe696",
|
||||||
|
"darwin_arm64": "bdc93f811e017affb893eab8d924dfe72ea63e1bdeaf85decec1afb711288ee5",
|
||||||
|
"darwin_amd64": "d44a4fd5526174788622e4eebea55ef268df19c85fc67766d0f27e23eb8800fa",
|
||||||
|
}
|
||||||
|
URL = "https://github.com/fosrl/newt/releases/download/{version}/newt_{plat}"
|
||||||
|
|
||||||
|
|
||||||
|
def platform_tag() -> str:
|
||||||
|
os_name = {"Linux": "linux", "Darwin": "darwin"}.get(platform.system())
|
||||||
|
arch = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower())
|
||||||
|
tag = f"{os_name}_{arch}"
|
||||||
|
if tag not in SHA256:
|
||||||
|
raise SystemExit(f"newt isn't packaged here for {platform.system()} {platform.machine()}")
|
||||||
|
return tag
|
||||||
|
|
||||||
|
|
||||||
|
def binary() -> "os.PathLike":
|
||||||
|
return paths.NEWT_DIR / "newt"
|
||||||
|
|
||||||
|
|
||||||
|
def installed_version():
|
||||||
|
try:
|
||||||
|
return (paths.NEWT_DIR / "VERSION").read_text().strip()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_binary(say=print, fetch=None) -> bool:
|
||||||
|
"""Install the pinned newt if it isn't there already. Returns True if it changed."""
|
||||||
|
if installed_version() == VERSION and binary().exists():
|
||||||
|
return False
|
||||||
|
tag = platform_tag()
|
||||||
|
url = URL.format(version=VERSION, plat=tag)
|
||||||
|
say(f"Downloading newt {VERSION} ({tag})…")
|
||||||
|
data = (fetch or _fetch)(url)
|
||||||
|
got = hashlib.sha256(data).hexdigest()
|
||||||
|
if got != SHA256[tag]:
|
||||||
|
raise SystemExit(f"newt download didn't match its checksum (got {got}); not installing it")
|
||||||
|
paths.NEWT_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd, tmp = tempfile.mkstemp(dir=paths.NEWT_DIR, prefix=".newt.")
|
||||||
|
with os.fdopen(fd, "wb") as f:
|
||||||
|
f.write(data)
|
||||||
|
os.chmod(tmp, 0o755)
|
||||||
|
os.replace(tmp, binary())
|
||||||
|
(paths.NEWT_DIR / "VERSION").write_text(VERSION + "\n")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch(url) -> bytes:
|
||||||
|
with urllib.request.urlopen(url, timeout=300) as r:
|
||||||
|
return r.read()
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
"""The service's entry point: exec newt with its credentials in the environment."""
|
||||||
|
cfg = paths.load_config()
|
||||||
|
conf = cfg.get("newt") or {}
|
||||||
|
if not conf.get("endpoint") or not conf.get("id"):
|
||||||
|
raise SystemExit("newt isn't configured; run `llmhost install-newt`")
|
||||||
|
secret = paths.read_secret(paths.NEWT_SECRET_FILE, "newt site secret", "llmhost install-newt")
|
||||||
|
env = {**os.environ, "PANGOLIN_ENDPOINT": conf["endpoint"], "NEWT_ID": conf["id"],
|
||||||
|
"NEWT_SECRET": secret, "LOG_LEVEL": conf.get("log_level", "INFO")}
|
||||||
|
exe = str(binary())
|
||||||
|
os.execve(exe, [exe], env)
|
||||||
|
|
@ -17,6 +17,7 @@ never overwritten. Other providers and settings are left untouched.
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -28,7 +29,8 @@ PROVIDER = "llmhost"
|
||||||
DISPLAY = "LLMHost"
|
DISPLAY = "LLMHost"
|
||||||
LOCAL_LABEL = "Local"
|
LOCAL_LABEL = "Local"
|
||||||
LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]")
|
LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]")
|
||||||
INSTALL_URL = "https://opencode.ai/install"
|
INSTALL_SCRIPT = paths.SRC / "opencode-install.sh"
|
||||||
|
DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too
|
||||||
|
|
||||||
|
|
||||||
def find():
|
def find():
|
||||||
|
|
@ -40,12 +42,70 @@ def find():
|
||||||
|
|
||||||
|
|
||||||
def install(log=print):
|
def install(log=print):
|
||||||
"""Run opencode's official installer (installs to ~/.opencode/bin, adds it to PATH)."""
|
"""Install opencode the way every machine does: through llm-host's opencode-install.sh,
|
||||||
log(f"$ curl -fsSL {INSTALL_URL} | bash")
|
which runs opencode's official installer (into ~/.opencode/bin, added to PATH). Only
|
||||||
r = subprocess.run(["bash", "-c", f"set -o pipefail; curl -fsSL {INSTALL_URL} | bash"])
|
the install step: this machine's provider is configure()'s, since it reads the key
|
||||||
|
file in place and is kept in sync on every switch."""
|
||||||
|
log(f"$ {INSTALL_SCRIPT.name} --install-only")
|
||||||
|
r = subprocess.run(["bash", str(INSTALL_SCRIPT), "--install-only"])
|
||||||
return find() if r.returncode == 0 else None
|
return find() if r.returncode == 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
def raw_file_url(repo, ref, name):
|
||||||
|
"""Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the
|
||||||
|
/raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https."""
|
||||||
|
m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "")
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
host, path = m.group(1), m.group(2)
|
||||||
|
if host.lower() == "github.com":
|
||||||
|
return f"https://raw.githubusercontent.com/{path}/{ref}/{name}"
|
||||||
|
return f"https://{host}/{path}/raw/branch/{ref}/{name}"
|
||||||
|
|
||||||
|
|
||||||
|
_installer = None
|
||||||
|
|
||||||
|
|
||||||
|
def installer_url():
|
||||||
|
"""opencode-install.sh's URL in the repo this server was installed from, so the command
|
||||||
|
handed to other machines follows a fork and needs nothing but the API to work. Falls
|
||||||
|
back to the main repo."""
|
||||||
|
global _installer
|
||||||
|
if _installer is None:
|
||||||
|
def git(*args):
|
||||||
|
try:
|
||||||
|
r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5)
|
||||||
|
return r.stdout.strip() if r.returncode == 0 else ""
|
||||||
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
return ""
|
||||||
|
ref = git("rev-parse", "--abbrev-ref", "HEAD")
|
||||||
|
_installer = (raw_file_url(git("config", "--get", "remote.origin.url"),
|
||||||
|
ref if ref and ref != "HEAD" else "main", INSTALL_SCRIPT.name)
|
||||||
|
or raw_file_url(DEFAULT_REPO, "main", INSTALL_SCRIPT.name))
|
||||||
|
return _installer
|
||||||
|
|
||||||
|
|
||||||
|
def remote_command(base_url):
|
||||||
|
"""The one line another machine runs to connect its opencode to this server."""
|
||||||
|
return f'/bin/bash -c "$(curl -fsSL {installer_url()})" -- --url {base_url}'
|
||||||
|
|
||||||
|
|
||||||
|
def client_targets(cfg, lan_host):
|
||||||
|
"""Where other machines reach the API, as [(where, base URL)], most useful first.
|
||||||
|
|
||||||
|
The API's public address (recorded by `llmhost install-newt`) when there is one, and
|
||||||
|
the local-network address too unless the dashboard is public -- a public dashboard
|
||||||
|
is seen from outside, where a LAN address is only noise."""
|
||||||
|
lan = ("on your local network", f"http://{lan_host}:{cfg['api_port']}")
|
||||||
|
public = (cfg.get("newt") or {}).get("api_url")
|
||||||
|
if not public:
|
||||||
|
return [lan]
|
||||||
|
out = [("from the internet", public)]
|
||||||
|
if not cfg.get("dashboard_public"):
|
||||||
|
out.append(lan)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def config_dir():
|
def config_dir():
|
||||||
return Path(os.environ.get("XDG_CONFIG_HOME") or paths.HOME / ".config") / "opencode"
|
return Path(os.environ.get("XDG_CONFIG_HOME") or paths.HOME / ".config") / "opencode"
|
||||||
|
|
||||||
|
|
@ -139,7 +199,7 @@ def effort_variants():
|
||||||
return {level: {"disabled": True} for level in OPENCODE_EFFORTS}
|
return {level: {"disabled": True} for level in OPENCODE_EFFORTS}
|
||||||
|
|
||||||
|
|
||||||
def provider_block(cfg, host, key_path, label, mark_loaded=False):
|
def provider_block(cfg, host, key_path, label, mark_loaded=False, base_url=None):
|
||||||
# A single entry, keyed by the alias the API also answers to. Listing every model that
|
# A single entry, keyed by the alias the API also answers to. Listing every model that
|
||||||
# fits would be a menu of four things that 404 and one that works, and naming the loaded
|
# fits would be a menu of four things that 404 and one that works, and naming the loaded
|
||||||
# one would break every client's saved default on each `llmhost switch`.
|
# one would break every client's saved default on each `llmhost switch`.
|
||||||
|
|
@ -157,7 +217,7 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False):
|
||||||
return {
|
return {
|
||||||
"npm": "@ai-sdk/openai-compatible",
|
"npm": "@ai-sdk/openai-compatible",
|
||||||
"name": f"{DISPLAY} ({label})",
|
"name": f"{DISPLAY} ({label})",
|
||||||
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)},
|
"options": {"baseURL": base_url or f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)},
|
||||||
"models": models,
|
"models": models,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
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"
|
||||||
|
|
@ -6,6 +6,10 @@ Layout (overridable with LLMHOST_HOME / LLMHOST_CONFIG):
|
||||||
~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA)
|
~/.local/share/llm-host/cuda merged CUDA toolkit built from pip wheels (NVIDIA)
|
||||||
~/.config/llm-host/config.json plan + settings
|
~/.config/llm-host/config.json plan + settings
|
||||||
~/.config/llm-host/api_key API key (0600)
|
~/.config/llm-host/api_key API key (0600)
|
||||||
|
~/.local/share/llm-host/newt newt binary, after `llmhost 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 json
|
||||||
import os
|
import os
|
||||||
|
|
@ -21,6 +25,10 @@ DATA = Path(os.environ.get("LLMHOST_HOME", HOME / ".local/share/llm-host"))
|
||||||
CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host"))
|
CONFIG_DIR = Path(os.environ.get("LLMHOST_CONFIG", HOME / ".config/llm-host"))
|
||||||
CONFIG_FILE = CONFIG_DIR / "config.json"
|
CONFIG_FILE = CONFIG_DIR / "config.json"
|
||||||
KEY_FILE = CONFIG_DIR / "api_key"
|
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")
|
LOG_DIR = (HOME / "Library/Logs/llm-host") if IS_MAC else (DATA / "logs")
|
||||||
BIN_DIR = HOME / ".local/bin"
|
BIN_DIR = HOME / ".local/bin"
|
||||||
SHIM = BIN_DIR / "llmhost"
|
SHIM = BIN_DIR / "llmhost"
|
||||||
|
|
@ -66,3 +74,23 @@ def api_key(create: bool = False) -> str:
|
||||||
with os.fdopen(fd, "w") as f:
|
with os.fdopen(fd, "w") as f:
|
||||||
f.write(key + "\n")
|
f.write(key + "\n")
|
||||||
return key
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def read_secret(path, what, fix) -> str:
|
||||||
|
try:
|
||||||
|
return path.read_text().strip()
|
||||||
|
except OSError:
|
||||||
|
raise SystemExit(f"No {what} at {path}; run `{fix}` again.")
|
||||||
|
|
||||||
|
|
||||||
|
def save_secret(path, secret: str) -> None:
|
||||||
|
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
with os.fdopen(fd, "w") as f:
|
||||||
|
f.write(secret + "\n")
|
||||||
|
os.chmod(path, 0o600) # O_CREAT's mode doesn't apply to a file that already existed
|
||||||
|
|
||||||
|
|
||||||
|
def oidc_secret() -> str:
|
||||||
|
return read_secret(OIDC_SECRET_FILE, "dashboard sign-in client secret", "llmhost install-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
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
"""Background services: systemd --user on Linux, launchd agents on macOS.
|
"""Background services: systemd --user on Linux, launchd agents on macOS.
|
||||||
|
|
||||||
Two services: "model" (the inference server) and "web" (dashboard). Both run `llmhost run-<name>`.
|
Two services: "model" (the inference server) and "web" (dashboard), plus "newt" (the
|
||||||
|
Pangolin tunnel) only after `llmhost install-newt`. Each runs `llmhost run-<name>`.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
|
@ -10,7 +11,8 @@ from pathlib import Path
|
||||||
|
|
||||||
from . import paths
|
from . import paths
|
||||||
|
|
||||||
NAMES = ("model", "web")
|
NAMES = ("model", "web") # what setup installs
|
||||||
|
OPTIONAL = ("newt",) # installed by their own command
|
||||||
|
|
||||||
|
|
||||||
def _run(cmd, timeout=60):
|
def _run(cmd, timeout=60):
|
||||||
|
|
@ -32,7 +34,8 @@ def _unit_path(name):
|
||||||
|
|
||||||
|
|
||||||
def _systemd_install(name):
|
def _systemd_install(name):
|
||||||
desc = {"model": "llm-host model server", "web": "llm-host dashboard"}[name]
|
desc = {"model": "llm-host model server", "web": "llm-host dashboard",
|
||||||
|
"newt": "llm-host tunnel (newt)"}[name]
|
||||||
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
|
extra = "TimeoutStartSec=1800\nTimeoutStopSec=60\n" if name == "model" else ""
|
||||||
p = _unit_path(name)
|
p = _unit_path(name)
|
||||||
p.parent.mkdir(parents=True, exist_ok=True)
|
p.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
@ -104,6 +107,10 @@ def install(name):
|
||||||
_run(["systemctl", "--user", "enable", _unit(name)])
|
_run(["systemctl", "--user", "enable", _unit(name)])
|
||||||
|
|
||||||
|
|
||||||
|
def installed(name):
|
||||||
|
return (_plist_path(name) if paths.IS_MAC else _unit_path(name)).exists()
|
||||||
|
|
||||||
|
|
||||||
def enable_linger():
|
def enable_linger():
|
||||||
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
|
"""Keep user services running without a login session (Linux). Often allowed without sudo."""
|
||||||
if paths.IS_MAC:
|
if paths.IS_MAC:
|
||||||
|
|
|
||||||
|
|
@ -76,13 +76,14 @@ button.small { font-size: 12px; padding: 4px 10px; }
|
||||||
}
|
}
|
||||||
.effort select:disabled { color: var(--muted); }
|
.effort select:disabled { color: var(--muted); }
|
||||||
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
|
.effort .s { color: var(--muted); font-size: 12px; margin-top: 7px; line-height: 1.45; }
|
||||||
button {
|
button, a.btn {
|
||||||
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
font: inherit; font-size: 13px; font-weight: 550; padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
||||||
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
|
border: 1px solid var(--border); background: var(--panel-2); color: var(--text);
|
||||||
}
|
}
|
||||||
button:hover:not(:disabled) { border-color: var(--faint); }
|
button:hover:not(:disabled) { border-color: var(--faint); }
|
||||||
button:disabled { opacity: .45; cursor: default; }
|
button:disabled { opacity: .45; cursor: default; }
|
||||||
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
a.btn { display: inline-block; text-decoration: none; }
|
||||||
|
button.primary, a.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
|
||||||
button.danger { color: var(--bad); }
|
button.danger { color: var(--bad); }
|
||||||
|
|
||||||
.profiles { display: flex; flex-direction: column; gap: 8px; }
|
.profiles { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
|
@ -157,6 +158,24 @@ 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 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 details.manual { margin-bottom: 12px; font-size: 13px; }
|
||||||
|
.dialog details.manual summary { cursor: pointer; color: var(--muted); margin-bottom: 8px; }
|
||||||
|
.dialog .snip pre.cmd { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
#cx-installs .where { font-size: 12.5px; color: var(--muted); margin: 0 0 4px; }
|
||||||
|
#cx-installs .snip { margin: 0 0 14px; }
|
||||||
.toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg);
|
.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; }
|
||||||
.toast.show { opacity: 1; }
|
.toast.show { opacity: 1; }
|
||||||
|
|
@ -169,6 +188,8 @@ pre {
|
||||||
<span id="phase" class="pill">…</span>
|
<span id="phase" class="pill">…</span>
|
||||||
<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>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
|
@ -244,8 +265,8 @@ pre {
|
||||||
<table>
|
<table>
|
||||||
<thead><tr>
|
<thead><tr>
|
||||||
<th>Finished</th><th>Duration</th><th>TTFT</th>
|
<th>Finished</th><th>Duration</th><th>TTFT</th>
|
||||||
<th>Prompt tok</th><th>Prompt tok/s</th>
|
<th>Prompt tok</th><th>Prompt sec</th><th>Prompt tok/s</th>
|
||||||
<th>Generated tok</th><th>Gen tok/s</th><th>Peak KV</th>
|
<th>Generated tok</th><th>Generated sec</th><th>Gen tok/s</th><th>Peak KV</th>
|
||||||
</tr></thead>
|
</tr></thead>
|
||||||
<tbody id="runs-body"></tbody>
|
<tbody id="runs-body"></tbody>
|
||||||
<tfoot id="runs-foot"></tfoot>
|
<tfoot id="runs-foot"></tfoot>
|
||||||
|
|
@ -262,12 +283,51 @@ pre {
|
||||||
|
|
||||||
<div class="overlay" id="auth">
|
<div class="overlay" id="auth">
|
||||||
<form class="dialog" id="auth-form">
|
<form class="dialog" id="auth-form">
|
||||||
<h3>API key</h3>
|
<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>
|
<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>
|
<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>
|
<div class="err" id="auth-err"></div>
|
||||||
<button class="primary" type="submit">Continue</button>
|
<button class="primary" type="submit">Continue</button>
|
||||||
</form>
|
</form>
|
||||||
|
<div class="dialog" id="auth-oidc" hidden>
|
||||||
|
<h3>Sign in</h3>
|
||||||
|
<p id="auth-oidc-text">This dashboard signs in through your identity provider.</p>
|
||||||
|
<a class="btn primary" href="/auth/login" id="auth-oidc-go">Sign in</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="overlay" id="connect-modal">
|
||||||
|
<div class="dialog wide" role="dialog" aria-modal="true" aria-labelledby="connect-title">
|
||||||
|
<h3 id="connect-title">Connect</h3>
|
||||||
|
<h4>API key</h4>
|
||||||
|
<p>For OpenAI-compatible clients, sent as <code>Authorization: Bearer <key></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>
|
||||||
|
|
||||||
|
<h4>Add to opencode</h4>
|
||||||
|
<p>Run this on the machine with opencode, or send it to whoever you're giving access, with the key. It needs
|
||||||
|
only the API, not this dashboard: it installs opencode if it's missing, asks for the key (hidden), saves it,
|
||||||
|
and adds this server to <code>opencode.json</code>, keeping their other settings.</p>
|
||||||
|
<div id="cx-installs"></div>
|
||||||
|
<details class="manual">
|
||||||
|
<summary id="cx-manual-title">Or set it up by hand</summary>
|
||||||
|
<ol>
|
||||||
|
<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;
|
||||||
|
if it already has settings, add the entry under <code>"provider"</code> to its own <code>"provider"</code>
|
||||||
|
(and set <code>"model"</code> only if you want this as the default):
|
||||||
|
<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>
|
</div>
|
||||||
<div class="toast" id="toast"></div>
|
<div class="toast" id="toast"></div>
|
||||||
|
|
||||||
|
|
@ -275,6 +335,9 @@ pre {
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
let KEY = null;
|
let KEY = null;
|
||||||
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
|
try { KEY = localStorage.getItem("llmhost-key"); } catch (e) {}
|
||||||
|
// "key": the API key, typed in and kept in this browser. "oidc": a session cookie set by
|
||||||
|
// signing in at the provider (/auth/login); the key isn't accepted then.
|
||||||
|
let AUTH = { mode: "key" };
|
||||||
let state = null;
|
let state = null;
|
||||||
let logTimer = null;
|
let logTimer = null;
|
||||||
|
|
||||||
|
|
@ -287,22 +350,152 @@ function toast(msg) {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function api(path, opts = {}) {
|
async function api(path, opts = {}) {
|
||||||
const r = await fetch(path, { ...opts, headers: { "Authorization": "Bearer " + KEY, "Content-Type": "application/json" } });
|
const headers = { "Content-Type": "application/json" };
|
||||||
if (r.status === 401) { showAuth("That key was rejected."); throw new Error("unauthorized"); }
|
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) {
|
||||||
|
if (useKey) showAuth("That key was rejected.");
|
||||||
|
else { AUTH.user = null; $("whoami").hidden = true; showAuth(""); }
|
||||||
|
throw new Error("unauthorized");
|
||||||
|
}
|
||||||
const body = await r.json();
|
const body = await r.json();
|
||||||
if (!r.ok) throw new Error(body.error || r.statusText);
|
if (!r.ok) throw new Error(body.error || r.statusText);
|
||||||
return body;
|
return body;
|
||||||
}
|
}
|
||||||
|
|
||||||
function showAuth(err = "") { $("auth-err").textContent = err; $("auth").classList.add("show"); $("auth-key").focus(); }
|
function showAuth(err = "") {
|
||||||
$("auth-form").addEventListener("submit", (e) => {
|
if (AUTH.mode === "oidc") {
|
||||||
|
$("auth-form").hidden = true; $("auth-oidc").hidden = false;
|
||||||
|
$("auth").classList.add("show"); $("auth-oidc-go").focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 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();
|
||||||
|
}
|
||||||
|
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();
|
e.preventDefault();
|
||||||
KEY = $("auth-key").value.trim();
|
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) {}
|
try { localStorage.setItem("llmhost-key", KEY); } catch (e) {}
|
||||||
|
}
|
||||||
$("auth").classList.remove("show");
|
$("auth").classList.remove("show");
|
||||||
poll();
|
poll();
|
||||||
});
|
});
|
||||||
$("logout").onclick = () => { try { localStorage.removeItem("llmhost-key"); } catch (e) {} KEY = null; showAuth(); };
|
async function copyText(text) {
|
||||||
|
try { await navigator.clipboard.writeText(text); return true; }
|
||||||
|
catch (e) {
|
||||||
|
// No clipboard API on plain http (a LAN address): fall back to a selected textarea.
|
||||||
|
const t = document.createElement("textarea"); t.value = text; t.style.position = "fixed"; t.style.opacity = "0";
|
||||||
|
document.body.appendChild(t); t.select();
|
||||||
|
let ok = false; try { ok = document.execCommand("copy"); } catch (e2) {}
|
||||||
|
t.remove(); return ok;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let CONNECT = null;
|
||||||
|
function closeConnect() {
|
||||||
|
$("connect-modal").classList.remove("show");
|
||||||
|
$("cx-key").value = ""; $("cx-key").type = "password"; $("cx-show").textContent = "Show";
|
||||||
|
CONNECT = null;
|
||||||
|
}
|
||||||
|
// opencode's provider block for the address typed in. The server sends the block from
|
||||||
|
// the same builder as `llmhost opencode-config`; only what depends on the address is
|
||||||
|
// filled in here: baseURL, and the provider id and label named after its host.
|
||||||
|
function renderOpencode() {
|
||||||
|
if (!CONNECT) return;
|
||||||
|
// One command per address the API is reached at (server's choice; see client_targets).
|
||||||
|
const box = $("cx-installs"); box.textContent = "";
|
||||||
|
for (const t of CONNECT.targets) {
|
||||||
|
if (CONNECT.targets.length > 1) {
|
||||||
|
const w = document.createElement("div"); w.className = "where";
|
||||||
|
w.textContent = t.where[0].toUpperCase() + t.where.slice(1) + ":"; box.appendChild(w);
|
||||||
|
}
|
||||||
|
const snip = document.createElement("div"); snip.className = "snip";
|
||||||
|
const pre = document.createElement("pre"); pre.className = "cmd"; pre.textContent = t.command;
|
||||||
|
const b = document.createElement("button"); b.className = "small"; b.textContent = "Copy";
|
||||||
|
b.onclick = async () => toast(await copyText(t.command) ? "Copied" : "Couldn't copy; select it and copy by hand");
|
||||||
|
snip.append(pre, b); box.appendChild(snip);
|
||||||
|
}
|
||||||
|
// By hand: for the first (most useful) address.
|
||||||
|
let url = CONNECT.targets[0].url.replace(/\/+$/, "");
|
||||||
|
$("cx-manual-title").textContent = `Or set it up by hand (for ${url})`;
|
||||||
|
let host = "";
|
||||||
|
try { host = new URL(url).hostname; } catch (e) {}
|
||||||
|
if (url && !/\/v1$/.test(url)) url += "/v1";
|
||||||
|
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);
|
||||||
|
// A whole config, like `llmhost opencode-config` prints: it works as-is in an empty
|
||||||
|
// file, and its "provider" entry is what to merge into an existing one.
|
||||||
|
$("cx-block").textContent = JSON.stringify({
|
||||||
|
$schema: "https://opencode.ai/config.json",
|
||||||
|
provider: { [prov]: block },
|
||||||
|
model: `${prov}/${CONNECT.model}`,
|
||||||
|
}, null, 2);
|
||||||
|
$("cx-keycmd").textContent =
|
||||||
|
// 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-pick").textContent = `${block.name} → ${Object.values(block.models)[0]?.name || CONNECT.model}`;
|
||||||
|
}
|
||||||
|
$("connect").onclick = async () => {
|
||||||
|
let c;
|
||||||
|
try { c = await api("/api/connect"); } catch (e) { if (e.message !== "unauthorized") toast("Couldn't load: " + e.message); return; }
|
||||||
|
CONNECT = c;
|
||||||
|
$("cx-key").value = c.key;
|
||||||
|
renderOpencode();
|
||||||
|
$("connect-modal").classList.add("show"); $("cx-close").focus();
|
||||||
|
};
|
||||||
|
document.querySelectorAll("#connect-modal [data-copy]").forEach((b) => {
|
||||||
|
b.onclick = async () => toast(await copyText($(b.dataset.copy).textContent) ? "Copied" : "Couldn't copy; select it and copy by hand");
|
||||||
|
});
|
||||||
|
$("cx-copy").onclick = async () => toast(await copyText($("cx-key").value) ? "Copied" : "Couldn't copy; select it and copy by hand");
|
||||||
|
$("cx-show").onclick = () => {
|
||||||
|
const k = $("cx-key"), hide = k.type === "text";
|
||||||
|
k.type = hide ? "password" : "text"; $("cx-show").textContent = hide ? "Show" : "Hide";
|
||||||
|
};
|
||||||
|
$("cx-close").onclick = closeConnect;
|
||||||
|
$("connect-modal").addEventListener("click", (e) => { if (e.target === $("connect-modal")) closeConnect(); });
|
||||||
|
document.addEventListener("keydown", (e) => { if (e.key === "Escape" && $("connect-modal").classList.contains("show")) closeConnect(); });
|
||||||
|
|
||||||
|
$("logout").onclick = async () => {
|
||||||
|
if (AUTH.mode === "oidc") {
|
||||||
|
try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch (e) {}
|
||||||
|
AUTH.user = null; $("whoami").hidden = true; clearTimeout(pollTimer); closeConnect(); showAuth();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
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 = {
|
const fmt = {
|
||||||
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
|
n: (v, d = 0) => v == null ? "—" : v.toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: d }),
|
||||||
|
|
@ -311,6 +504,15 @@ const fmt = {
|
||||||
dur: (s) => { if (s == null) return ""; s = Math.floor(s); const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
|
dur: (s) => { if (s == null) return ""; s = Math.floor(s); const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
|
||||||
return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; },
|
return d ? `${d}d ${h}h` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; },
|
||||||
secs: (v) => v == null ? "—" : v < 1 ? Math.round(v * 1000) + " ms" : v < 10 ? v.toFixed(2) + " s" : v.toFixed(1) + " s",
|
secs: (v) => v == null ? "—" : v < 1 ? Math.round(v * 1000) + " ms" : v < 10 ? v.toFixed(2) + " s" : v.toFixed(1) + " s",
|
||||||
|
// A request's own clock: seconds while that reads precisely, then minutes and hours as
|
||||||
|
// it passes them -- never a unit the value hasn't reached.
|
||||||
|
span: (v) => {
|
||||||
|
if (v == null) return "—";
|
||||||
|
if (v < 60) return fmt.secs(v);
|
||||||
|
const t = Math.round(v), h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), s = t % 60;
|
||||||
|
const pad = (n) => String(n).padStart(2, "0");
|
||||||
|
return h ? `${h}h ${pad(m)}m ${pad(s)}s` : `${m}m ${pad(s)}s`;
|
||||||
|
},
|
||||||
ctx: (n) => n == null ? "" : n >= 1024 ? Math.round(n / 1024) + "k ctx" : n + " ctx",
|
ctx: (n) => n == null ? "" : n >= 1024 ? Math.round(n / 1024) + "k ctx" : n + " ctx",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -512,11 +714,13 @@ function renderRuns(s) {
|
||||||
const tr = document.createElement("tr");
|
const tr = document.createElement("tr");
|
||||||
if (r.aborted) tr.className = "aborted";
|
if (r.aborted) tr.className = "aborted";
|
||||||
cell(tr, clock(r.t));
|
cell(tr, clock(r.t));
|
||||||
cell(tr, ...dash(r.dur, fmt.secs));
|
cell(tr, ...dash(r.dur, fmt.span));
|
||||||
cell(tr, ...dash(r.ttft, fmt.secs));
|
cell(tr, ...dash(r.ttft, fmt.span));
|
||||||
cell(tr, ...dash(r.prompt, (v) => fmt.big(v)));
|
cell(tr, ...dash(r.prompt, (v) => fmt.big(v)));
|
||||||
|
cell(tr, ...dash(r.prompt_s, fmt.span));
|
||||||
cell(tr, ...dash(r.prompt_tps, (v) => fmt.n(v, 0)));
|
cell(tr, ...dash(r.prompt_tps, (v) => fmt.n(v, 0)));
|
||||||
cell(tr, ...dash(r.gen, (v) => fmt.big(v)));
|
cell(tr, ...dash(r.gen, (v) => fmt.big(v)));
|
||||||
|
cell(tr, ...dash(r.gen_s, fmt.span));
|
||||||
cell(tr, ...dash(r.gen_tps, (v) => fmt.n(v, 1)));
|
cell(tr, ...dash(r.gen_tps, (v) => fmt.n(v, 1)));
|
||||||
cell(tr, ...dash(r.kv_peak_pct, (v) => fmt.n(v, 1) + "%"));
|
cell(tr, ...dash(r.kv_peak_pct, (v) => fmt.n(v, 1) + "%"));
|
||||||
body.append(tr);
|
body.append(tr);
|
||||||
|
|
@ -529,15 +733,18 @@ function renderRuns(s) {
|
||||||
const peak = Math.max(...runs.map((r) => r.kv_peak_pct ?? 0));
|
const peak = Math.max(...runs.map((r) => r.kv_peak_pct ?? 0));
|
||||||
const tr = document.createElement("tr");
|
const tr = document.createElement("tr");
|
||||||
cell(tr, `${runs.length} shown`);
|
cell(tr, `${runs.length} shown`);
|
||||||
cell(tr, ...dash(avg("dur"), fmt.secs));
|
cell(tr, ...dash(avg("dur"), fmt.span));
|
||||||
cell(tr, ...dash(avg("ttft"), fmt.secs));
|
cell(tr, ...dash(avg("ttft"), fmt.span));
|
||||||
cell(tr, ...dash(avg("prompt"), (v) => fmt.big(v)));
|
cell(tr, ...dash(avg("prompt"), (v) => fmt.big(v)));
|
||||||
|
cell(tr, ...dash(avg("prompt_s"), fmt.span));
|
||||||
cell(tr, ...dash(avg("prompt_tps"), (v) => fmt.n(v, 0)));
|
cell(tr, ...dash(avg("prompt_tps"), (v) => fmt.n(v, 0)));
|
||||||
cell(tr, ...dash(avg("gen"), (v) => fmt.big(v)));
|
cell(tr, ...dash(avg("gen"), (v) => fmt.big(v)));
|
||||||
|
cell(tr, ...dash(avg("gen_s"), fmt.span));
|
||||||
cell(tr, ...dash(avg("gen_tps"), (v) => fmt.n(v, 1)));
|
cell(tr, ...dash(avg("gen_tps"), (v) => fmt.n(v, 1)));
|
||||||
cell(tr, ...dash(peak > 0 ? peak : null, (v) => fmt.n(v, 1) + "%"));
|
cell(tr, ...dash(peak > 0 ? peak : null, (v) => fmt.n(v, 1) + "%"));
|
||||||
foot.append(tr);
|
foot.append(tr);
|
||||||
$("runs-sub").textContent = "newest first · averages below · tok/s split at first token";
|
$("runs-sub").textContent = "newest first · averages below · phases split at the first token; "
|
||||||
|
+ "a request that didn't stream has none, so all of it counts as generation";
|
||||||
}
|
}
|
||||||
|
|
||||||
const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples
|
const CW = 300, CH = 90, CN = 300; // chart viewBox width/height, max samples
|
||||||
|
|
@ -678,12 +885,24 @@ $("logs").addEventListener("toggle", () => {
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
async function poll() {
|
async function poll() {
|
||||||
clearTimeout(pollTimer);
|
clearTimeout(pollTimer);
|
||||||
if (!KEY) { showAuth(); return; }
|
if (AUTH.mode === "key" ? !(KEY && AUTH.key !== false) && !AUTH.user : !AUTH.user) { showAuth(); return; }
|
||||||
try { render(await api("/api/status")); }
|
try { render(await api("/api/status")); }
|
||||||
catch (e) { if (e.message !== "unauthorized") { $("phase").textContent = "Dashboard unreachable"; $("phase").className = "pill failed"; } }
|
catch (e) {
|
||||||
|
if (e.message === "unauthorized" && !(AUTH.mode === "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);
|
pollTimer = setTimeout(poll, 2000);
|
||||||
}
|
}
|
||||||
poll();
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
const r = await fetch("/auth/config", { credentials: "same-origin" });
|
||||||
|
if (r.ok) AUTH = await r.json();
|
||||||
|
} catch (e) {}
|
||||||
|
if (AUTH.mode === "oidc" || AUTH.otp) $("logout").title = "Sign out of this dashboard";
|
||||||
|
if (AUTH.user) signedIn(AUTH.user, AUTH.name);
|
||||||
|
poll();
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
206
llmhost/web/oidc.py
Normal file
206
llmhost/web/oidc.py
Normal file
|
|
@ -0,0 +1,206 @@
|
||||||
|
"""Dashboard sign-in through an OpenID Connect provider. Stdlib only.
|
||||||
|
|
||||||
|
Off unless config.json has a "dashboard_auth" block with mode "oidc" (`llmhost install-newt` sets it); then it replaces the
|
||||||
|
API key on the dashboard (the API on api_port still takes the key -- that's for clients).
|
||||||
|
|
||||||
|
The flow is the authorization-code flow of a confidential client, with PKCE:
|
||||||
|
|
||||||
|
/auth/login -> 302 to the provider, with state, nonce and an S256 code challenge.
|
||||||
|
The state is also set in a short-lived cookie, so a callback only
|
||||||
|
completes in the browser that started it (no login CSRF).
|
||||||
|
/auth/callback -> code exchanged at the token endpoint with the client secret, the
|
||||||
|
ID token's claims checked, groups read from userinfo, the allow
|
||||||
|
list applied, and a session cookie set.
|
||||||
|
/auth/logout -> POST; drops the session.
|
||||||
|
|
||||||
|
The ID token comes straight from the token endpoint over TLS, which OIDC Core 3.1.3.7 lets
|
||||||
|
a client rely on in place of checking its signature; its iss/aud/azp/exp/nonce are still
|
||||||
|
checked. Sessions live in memory, so a dashboard restart signs everyone out.
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import secrets
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
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"
|
||||||
|
LOGIN_TTL = 600 # how long a started sign-in may take to come back
|
||||||
|
MAX_PENDING = 256 # unfinished sign-ins kept at once
|
||||||
|
CLOCK_SKEW = 120
|
||||||
|
SCOPES = "openid profile email groups"
|
||||||
|
|
||||||
|
|
||||||
|
class AuthError(Exception):
|
||||||
|
"""A sign-in that can't complete; the message is safe to show the user."""
|
||||||
|
|
||||||
|
|
||||||
|
def b64url(raw: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||||
|
|
||||||
|
|
||||||
|
def jwt_claims(token: str) -> dict:
|
||||||
|
try:
|
||||||
|
payload = token.split(".")[1]
|
||||||
|
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
|
||||||
|
except (IndexError, ValueError):
|
||||||
|
raise AuthError("the provider sent an unreadable ID token")
|
||||||
|
|
||||||
|
|
||||||
|
def origin_of(url: str) -> str:
|
||||||
|
u = urllib.parse.urlsplit(url)
|
||||||
|
return f"{u.scheme}://{u.netloc}".lower()
|
||||||
|
|
||||||
|
|
||||||
|
class OIDC:
|
||||||
|
def __init__(self, conf: dict, client_secret: str, http=None):
|
||||||
|
self.issuer = conf["issuer"].rstrip("/")
|
||||||
|
self.client_id = conf["client_id"]
|
||||||
|
self.secret = client_secret
|
||||||
|
self.public_url = conf["public_url"].rstrip("/")
|
||||||
|
self.redirect_uri = self.public_url + "/auth/callback"
|
||||||
|
self.origin = origin_of(self.public_url)
|
||||||
|
self.secure = self.public_url.startswith("https://")
|
||||||
|
self.allowed_groups = set(conf.get("allowed_groups") or [])
|
||||||
|
self.allowed_users = set(conf.get("allowed_users") or [])
|
||||||
|
if not (self.allowed_groups or self.allowed_users):
|
||||||
|
raise ValueError("dashboard_auth needs allowed_groups or allowed_users")
|
||||||
|
self.http = http or self._http
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.pending = {} # state -> {nonce, verifier, t}
|
||||||
|
self.store = Sessions()
|
||||||
|
self.sessions = self.store.items # sha256(session id) -> {user, name, exp}
|
||||||
|
self._disco = None
|
||||||
|
|
||||||
|
# -- provider ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _http(method, url, data=None, headers=None):
|
||||||
|
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=10) as r:
|
||||||
|
return r.status, r.read()
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return e.code, e.read()
|
||||||
|
|
||||||
|
def discovery(self) -> dict:
|
||||||
|
if self._disco is None:
|
||||||
|
try:
|
||||||
|
st, body = self.http("GET", self.issuer + "/.well-known/openid-configuration")
|
||||||
|
d = json.loads(body) if st == 200 else None
|
||||||
|
except (OSError, ValueError):
|
||||||
|
d = None
|
||||||
|
if not d or d.get("issuer", "").rstrip("/") != self.issuer:
|
||||||
|
raise AuthError(f"couldn't reach the sign-in provider at {self.issuer}")
|
||||||
|
self._disco = d
|
||||||
|
return self._disco
|
||||||
|
|
||||||
|
# -- sign-in ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
"""Begin a sign-in: (provider URL to redirect to, state for the state cookie)."""
|
||||||
|
d = self.discovery()
|
||||||
|
state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
|
||||||
|
now = time.time()
|
||||||
|
with self.lock:
|
||||||
|
for s in [s for s, p in self.pending.items() if now - p["t"] > LOGIN_TTL]:
|
||||||
|
del self.pending[s]
|
||||||
|
if len(self.pending) >= MAX_PENDING:
|
||||||
|
del self.pending[min(self.pending, key=lambda s: self.pending[s]["t"])]
|
||||||
|
self.pending[state] = {"nonce": nonce, "verifier": verifier, "t": now}
|
||||||
|
q = urllib.parse.urlencode({
|
||||||
|
"response_type": "code", "client_id": self.client_id, "redirect_uri": self.redirect_uri,
|
||||||
|
"scope": SCOPES, "state": state, "nonce": nonce,
|
||||||
|
"code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
|
||||||
|
"code_challenge_method": "S256"})
|
||||||
|
return f"{d['authorization_endpoint']}?{q}", state
|
||||||
|
|
||||||
|
def finish(self, params: dict, cookie_state: str) -> dict:
|
||||||
|
"""Complete a sign-in from the callback's query. Returns the new session
|
||||||
|
{"id", "user", "name"}; raises AuthError for anything that doesn't check out."""
|
||||||
|
if params.get("error"):
|
||||||
|
raise AuthError(f"the provider said: {params.get('error_description') or params['error']}")
|
||||||
|
state = params.get("state", "")
|
||||||
|
if not state or not cookie_state or not hmac.compare_digest(state, cookie_state):
|
||||||
|
raise AuthError("this sign-in was started in a different browser or tab; try again")
|
||||||
|
with self.lock:
|
||||||
|
p = self.pending.pop(state, None)
|
||||||
|
if not p or time.time() - p["t"] > LOGIN_TTL:
|
||||||
|
raise AuthError("this sign-in expired; try again")
|
||||||
|
d = self.discovery()
|
||||||
|
if "iss" in params and params["iss"].rstrip("/") != self.issuer:
|
||||||
|
raise AuthError("the response came from a different provider")
|
||||||
|
code = params.get("code")
|
||||||
|
if not code:
|
||||||
|
raise AuthError("the provider sent no authorization code")
|
||||||
|
|
||||||
|
basic = base64.b64encode(f"{urllib.parse.quote(self.client_id, safe='')}:"
|
||||||
|
f"{urllib.parse.quote(self.secret, safe='')}".encode()).decode()
|
||||||
|
st, body = self.http("POST", d["token_endpoint"], urllib.parse.urlencode({
|
||||||
|
"grant_type": "authorization_code", "code": code, "redirect_uri": self.redirect_uri,
|
||||||
|
"code_verifier": p["verifier"]}).encode(), {
|
||||||
|
"Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
"Accept": "application/json"})
|
||||||
|
try:
|
||||||
|
tok = json.loads(body)
|
||||||
|
except ValueError:
|
||||||
|
tok = {}
|
||||||
|
if st != 200 or "id_token" not in tok:
|
||||||
|
raise AuthError(f"the provider refused the code ({tok.get('error') or st})")
|
||||||
|
|
||||||
|
c = jwt_claims(tok["id_token"])
|
||||||
|
now = time.time()
|
||||||
|
aud = c.get("aud")
|
||||||
|
auds = aud if isinstance(aud, list) else [aud]
|
||||||
|
if c.get("iss", "").rstrip("/") != self.issuer:
|
||||||
|
raise AuthError("the ID token is from a different provider")
|
||||||
|
if self.client_id not in auds or (len(auds) > 1 and c.get("azp") != self.client_id):
|
||||||
|
raise AuthError("the ID token was issued to a different client")
|
||||||
|
if not isinstance(c.get("exp"), (int, float)) or c["exp"] < now - CLOCK_SKEW:
|
||||||
|
raise AuthError("the ID token has expired")
|
||||||
|
if not hmac.compare_digest(str(c.get("nonce", "")), p["nonce"]):
|
||||||
|
raise AuthError("the ID token doesn't belong to this sign-in")
|
||||||
|
|
||||||
|
info = dict(c)
|
||||||
|
if d.get("userinfo_endpoint") and tok.get("access_token"):
|
||||||
|
st, body = self.http("GET", d["userinfo_endpoint"], None, {
|
||||||
|
"Authorization": f"Bearer {tok['access_token']}", "Accept": "application/json"})
|
||||||
|
try:
|
||||||
|
u = json.loads(body) if st == 200 else {}
|
||||||
|
except ValueError:
|
||||||
|
u = {} # a signed/encrypted userinfo isn't JSON; the ID token's claims stand
|
||||||
|
if u.get("sub") == c.get("sub"):
|
||||||
|
info.update(u)
|
||||||
|
|
||||||
|
user = info.get("preferred_username") or info.get("email") or info.get("sub")
|
||||||
|
groups = set(info.get("groups") or [])
|
||||||
|
if user not in self.allowed_users and not (groups & self.allowed_groups):
|
||||||
|
raise AuthError(f"signed in as {user}, but that account isn't allowed on this dashboard")
|
||||||
|
|
||||||
|
sid = self.store.create(user, info.get("name") or user)
|
||||||
|
return {"id": sid, "user": user, "name": info.get("name") or user}
|
||||||
|
|
||||||
|
# -- sessions ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
def session(self, cookie_header: str):
|
||||||
|
return self.store.get(cookie_header)
|
||||||
|
|
||||||
|
def end(self, cookie_header: str):
|
||||||
|
self.store.end(cookie_header)
|
||||||
|
|
||||||
|
def same_origin(self, headers) -> bool:
|
||||||
|
"""For state-changing requests: the browser's Origin (or Referer) must be the
|
||||||
|
dashboard's own. SameSite=Lax already keeps the cookie off cross-site POSTs;
|
||||||
|
this is the second lock on that door."""
|
||||||
|
o = headers.get("Origin") or (origin_of(headers["Referer"]) if headers.get("Referer") else "")
|
||||||
|
return o.lower() == self.origin
|
||||||
|
|
||||||
|
def cookie(self, name, value, max_age, path="/"):
|
||||||
|
return make_cookie(name, value, max_age, self.secure, path)
|
||||||
|
|
@ -1,19 +1,28 @@
|
||||||
"""Dashboard: status, metrics and model switching. Stdlib only.
|
"""Dashboard: status, metrics and model switching. Stdlib only.
|
||||||
|
|
||||||
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key.
|
Serves index.html and a JSON API on cfg["web_port"]. 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 hmac
|
||||||
|
import html
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .. import hfcache, hw, opencode, paths, plan, service
|
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
|
HERE = Path(__file__).resolve().parent
|
||||||
SAMPLE_SECONDS = 2
|
SAMPLE_SECONDS = 2
|
||||||
|
|
@ -94,6 +103,30 @@ def run_kv_peak(history, run, now, current):
|
||||||
return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None
|
return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None
|
||||||
|
|
||||||
|
|
||||||
|
def run_phases(r):
|
||||||
|
"""How long a run spent on each phase, and the rate of each. Time to first token
|
||||||
|
covers the prompt's prefill (queueing with it, there being nothing finer to measure
|
||||||
|
from), and what's left of the duration is generation; a rate over the whole duration
|
||||||
|
would blur the two together.
|
||||||
|
|
||||||
|
A run that didn't stream has no first-token mark and so no split: its prompt time is
|
||||||
|
unknown and its whole duration is charged to generation -- which the table says, by
|
||||||
|
showing no prompt seconds beside it."""
|
||||||
|
dur, ttft = r.get("dur") or 0, r.get("ttft")
|
||||||
|
prompt_s = ttft
|
||||||
|
gen_s = (dur - ttft) if (ttft is not None and dur > ttft) else dur
|
||||||
|
return {"prompt_s": prompt_s, "gen_s": gen_s or None,
|
||||||
|
"prompt_tps": (r["prompt"] / prompt_s) if (prompt_s and r.get("prompt")) else None,
|
||||||
|
"gen_tps": (r["gen"] / gen_s) if (gen_s and r.get("gen")) else None}
|
||||||
|
|
||||||
|
|
||||||
|
def run_row(r, kv_peak):
|
||||||
|
"""One finished request as the dashboard's table wants it."""
|
||||||
|
return {"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
|
||||||
|
"prompt": r.get("prompt"), "ttft": r.get("ttft"), **run_phases(r),
|
||||||
|
"kv_peak_pct": kv_peak, "aborted": bool(r.get("aborted"))}
|
||||||
|
|
||||||
|
|
||||||
def parse_vllm_metrics(text):
|
def parse_vllm_metrics(text):
|
||||||
vals = {}
|
vals = {}
|
||||||
for line in text.splitlines():
|
for line in text.splitlines():
|
||||||
|
|
@ -227,15 +260,6 @@ class Sampler:
|
||||||
def ratio(a, b):
|
def ratio(a, b):
|
||||||
return shown[a] / shown[b] if shown.get(b) else None
|
return shown[a] / shown[b] if shown.get(b) else None
|
||||||
|
|
||||||
def run_rates(r):
|
|
||||||
"""Split a run into its two phases: time to first token covers the prefill, the
|
|
||||||
rest is generation. Rates over the whole duration would blur the two together."""
|
|
||||||
dur, ttft = r.get("dur") or 0, r.get("ttft")
|
|
||||||
prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
|
|
||||||
gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur
|
|
||||||
gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None
|
|
||||||
return gen_tps, prompt_tps
|
|
||||||
|
|
||||||
last_log = None
|
last_log = None
|
||||||
if phase in ("loading", "failed"):
|
if phase in ("loading", "failed"):
|
||||||
lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)]
|
lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)]
|
||||||
|
|
@ -254,14 +278,7 @@ class Sampler:
|
||||||
if key in self._seen_runs or r.get("start") is None:
|
if key in self._seen_runs or r.get("start") is None:
|
||||||
continue
|
continue
|
||||||
self._seen_runs.add(key)
|
self._seen_runs.add(key)
|
||||||
gen_tps, prompt_tps = run_rates(r)
|
self.runs.append(run_row(r, run_kv_peak(self.history, r, now, point["kv"])))
|
||||||
self.runs.append({
|
|
||||||
"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
|
|
||||||
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
|
|
||||||
"gen_tps": gen_tps, "prompt_tps": prompt_tps,
|
|
||||||
"kv_peak_pct": run_kv_peak(self.history, r, now, point["kv"]),
|
|
||||||
"aborted": bool(r.get("aborted")),
|
|
||||||
})
|
|
||||||
if len(self._seen_runs) > 4 * RUNS_SHOWN:
|
if len(self._seen_runs) > 4 * RUNS_SHOWN:
|
||||||
# The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the
|
# The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the
|
||||||
# oldest keys can't resurrect a run we already have.
|
# oldest keys can't resurrect a run we already have.
|
||||||
|
|
@ -400,7 +417,15 @@ class Sampler:
|
||||||
threading.Thread(target=fn, args=("model",), daemon=True).start()
|
threading.Thread(target=fn, args=("model",), daemon=True).start()
|
||||||
|
|
||||||
|
|
||||||
def make_handler(sampler, key):
|
# The opencode installer's URL is worked out once, from the repo this was installed from.
|
||||||
|
raw_file_url, installer_url = opencode.raw_file_url, opencode.installer_url
|
||||||
|
|
||||||
|
|
||||||
|
def make_handler(sampler, key, oidc=None, otp=None, key_login=True):
|
||||||
|
"""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):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
server_version = "llm-host"
|
server_version = "llm-host"
|
||||||
|
|
||||||
|
|
@ -417,15 +442,120 @@ def make_handler(sampler, key):
|
||||||
self.wfile.write(body)
|
self.wfile.write(body)
|
||||||
|
|
||||||
def authed(self):
|
def authed(self):
|
||||||
|
if oidc:
|
||||||
|
# Signed in through the provider; the API key isn't accepted here.
|
||||||
|
if oidc.session(self.headers.get("Cookie", "")) is None:
|
||||||
|
self.send_json(401, {"error": "unauthorized", "login": "/auth/login"})
|
||||||
|
return False
|
||||||
|
if self.command == "POST" and not oidc.same_origin(self.headers):
|
||||||
|
self.send_json(403, {"error": "cross-origin request refused"})
|
||||||
|
return False
|
||||||
|
return True
|
||||||
h = self.headers.get("Authorization", "")
|
h = self.headers.get("Authorization", "")
|
||||||
tok = h[7:] if h.startswith("Bearer ") else ""
|
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
|
return True
|
||||||
self.send_json(401, {"error": "unauthorized"})
|
self.send_json(401, {"error": "unauthorized"})
|
||||||
return False
|
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)
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
for c in cookies:
|
||||||
|
self.send_header("Set-Cookie", c)
|
||||||
|
self.send_header("Content-Length", "0")
|
||||||
|
self.end_headers()
|
||||||
|
|
||||||
|
def auth_page(self, code, msg):
|
||||||
|
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
|
||||||
|
f"<title>llm-host sign-in</title><body style='font:15px system-ui;margin:3em auto;"
|
||||||
|
f"max-width:32em;padding:0 16px'><h2>Couldn't sign you in</h2><p>{html.escape(msg)}</p>"
|
||||||
|
f"<p><a href='/auth/login'>Try again</a></p>").encode()
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
|
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/"))
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def on_public_host(self):
|
||||||
|
"""A session cookie only exists on the public URL's host, so a visit by any
|
||||||
|
other name (mybox.local:11340) is sent there instead of to a login loop."""
|
||||||
|
host = (self.headers.get("Host") or "").lower()
|
||||||
|
return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower()
|
||||||
|
|
||||||
|
def auth_get(self, path, query):
|
||||||
|
if path == "/auth/config":
|
||||||
|
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"})
|
||||||
|
if path == "/auth/login":
|
||||||
|
if not self.on_public_host():
|
||||||
|
return self.redirect(oidc.public_url + "/auth/login")
|
||||||
|
try:
|
||||||
|
url, state = oidc.start()
|
||||||
|
except oidc_mod.AuthError as e:
|
||||||
|
return self.auth_page(502, str(e))
|
||||||
|
return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")])
|
||||||
|
if path == "/auth/callback":
|
||||||
|
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
|
||||||
|
cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "")
|
||||||
|
try:
|
||||||
|
s = oidc.finish(params, cookie_state)
|
||||||
|
except oidc_mod.AuthError as e:
|
||||||
|
return self.auth_page(403, str(e))
|
||||||
|
print(f"llm-host dashboard: {s['user']} signed in", flush=True)
|
||||||
|
return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL),
|
||||||
|
oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")])
|
||||||
|
self.send_json(404, {"error": "not found"})
|
||||||
|
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
path = self.path.split("?", 1)[0]
|
path, _, query = self.path.partition("?")
|
||||||
|
if path.startswith("/auth/"):
|
||||||
|
return self.auth_get(path, query)
|
||||||
|
if oidc and path in ("/", "/index.html") and not self.on_public_host():
|
||||||
|
return self.redirect(oidc.public_url + "/")
|
||||||
if path in ("/", "/index.html"):
|
if path in ("/", "/index.html"):
|
||||||
body = (HERE / "index.html").read_bytes()
|
body = (HERE / "index.html").read_bytes()
|
||||||
self.send_response(200)
|
self.send_response(200)
|
||||||
|
|
@ -437,6 +567,20 @@ def make_handler(sampler, key):
|
||||||
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/connect":
|
||||||
|
# What the Connect dialog hands to clients: the key; the API's addresses with
|
||||||
|
# the opencode-install.sh command for each, chosen by the same rule as setup and
|
||||||
|
# `llmhost opencode-config` (opencode.client_targets); and opencode's provider
|
||||||
|
# block for setting it up by hand, whose address-dependent parts the page fills
|
||||||
|
# in. Behind the same sign-in as everything else; send_json marks it no-store.
|
||||||
|
if self.authed():
|
||||||
|
cfg = paths.load_config() or sampler.cfg
|
||||||
|
h = socket.gethostname()
|
||||||
|
targets = [{"where": w, "url": u, "command": opencode.remote_command(u)}
|
||||||
|
for w, u in opencode.client_targets(cfg, h if "." in h else h + ".local")]
|
||||||
|
block = opencode.provider_block(cfg, "HOST", "KEYFILE", "LABEL")
|
||||||
|
self.send_json(200, {"key": key, "model": plan.SERVED_ALIAS, "opencode": block,
|
||||||
|
"targets": targets})
|
||||||
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)
|
||||||
|
|
@ -447,6 +591,29 @@ def make_handler(sampler, key):
|
||||||
|
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
path = self.path.split("?", 1)[0]
|
path = self.path.split("?", 1)[0]
|
||||||
|
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 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():
|
if not self.authed():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
|
|
@ -486,6 +653,15 @@ def serve():
|
||||||
key = paths.api_key()
|
key = paths.api_key()
|
||||||
sampler = Sampler(cfg, key)
|
sampler = Sampler(cfg, key)
|
||||||
threading.Thread(target=sampler.loop, daemon=True).start()
|
threading.Thread(target=sampler.loop, daemon=True).start()
|
||||||
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key))
|
auth = otp = None
|
||||||
print(f"llm-host dashboard on :{cfg['web_port']}", flush=True)
|
conf = cfg.get("dashboard_auth") or {}
|
||||||
|
if conf.get("mode") == "oidc":
|
||||||
|
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
|
||||||
|
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()
|
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)
|
||||||
327
opencode-install.sh
Executable file
327
opencode-install.sh
Executable file
|
|
@ -0,0 +1,327 @@
|
||||||
|
#!/bin/bash
|
||||||
|
# Connect opencode to an llm-host server -- installing opencode first if it isn't there.
|
||||||
|
#
|
||||||
|
# /bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/opencode-install.sh)" \
|
||||||
|
# -- --url https://llm-api.example.com
|
||||||
|
#
|
||||||
|
# It needs only the API's address and key: not llm-host, and not its dashboard.
|
||||||
|
#
|
||||||
|
# It asks for the API key (hidden). To pass it instead, use --key or $LLMHOST_API_KEY;
|
||||||
|
# note that a key given on the command line ends up in your shell history.
|
||||||
|
#
|
||||||
|
# What it does, all in your home directory (no sudo):
|
||||||
|
# 1. checks the server answers with that key
|
||||||
|
# 2. installs opencode with the official installer, unless it's already installed
|
||||||
|
# 3. saves the key to ~/.config/opencode/llmhost-<host>.key (mode 600)
|
||||||
|
# 4. adds an llmhost-<host> provider to ~/.config/opencode/opencode.json, keeping
|
||||||
|
# everything else in it (backed up first as opencode.json.before-llmhost), and
|
||||||
|
# makes it the default model if you have none (or say so)
|
||||||
|
# 5. drops any key opencode cached for that provider, so the key file is what it uses
|
||||||
|
#
|
||||||
|
# Options:
|
||||||
|
# --url URL the API's address (https://host or https://host/v1)
|
||||||
|
# --key KEY the API key (default: $LLMHOST_API_KEY, else asked for)
|
||||||
|
# --default make it opencode's default model without asking
|
||||||
|
# --no-default leave opencode's default model alone
|
||||||
|
# --skip-install don't install opencode, only configure it
|
||||||
|
# --install-only only install opencode (no --url or key needed); `llmhost setup` uses this
|
||||||
|
# --remove take this server back out of opencode's config
|
||||||
|
# Written for bash 3.2 so it runs on stock macOS.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if [ -t 1 ]; then B=$'\033[1m'; R=$'\033[31m'; Y=$'\033[33m'; G=$'\033[32m'; N=$'\033[0m'; else B=""; R=""; Y=""; G=""; N=""; fi
|
||||||
|
say() { printf '%s==>%s %s\n' "$B" "$N" "$*"; }
|
||||||
|
warn() { printf '%sWarning:%s %s\n' "$Y" "$N" "$*" >&2; }
|
||||||
|
die() { printf '%sError:%s %s\n' "$R" "$N" "$*" >&2; exit 1; }
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat <<'EOF'
|
||||||
|
Connect opencode to an llm-host server, installing opencode first if needed.
|
||||||
|
|
||||||
|
opencode-install.sh --url https://llm-api.example.com [options]
|
||||||
|
|
||||||
|
--url URL the API's address (https://host or https://host/v1)
|
||||||
|
--key KEY the API key (default: $LLMHOST_API_KEY, else asked for, hidden)
|
||||||
|
--default make it opencode's default model without asking
|
||||||
|
--no-default leave opencode's default model alone
|
||||||
|
--skip-install don't install opencode, only configure it
|
||||||
|
--install-only only install opencode (no --url or key needed)
|
||||||
|
--remove take this server back out of opencode's config
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
[ "${1:-}" = "--" ] && shift
|
||||||
|
URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0; INSTALL_ONLY=0
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--url) URL="${2:-}"; shift 2 ;;
|
||||||
|
--url=*) URL="${1#*=}"; shift ;;
|
||||||
|
--key) KEY="${2:-}"; shift 2 ;;
|
||||||
|
--key=*) KEY="${1#*=}"; shift ;;
|
||||||
|
--default) DEFAULT="yes"; shift ;;
|
||||||
|
--no-default) DEFAULT="no"; shift ;;
|
||||||
|
--skip-install) INSTALL=0; shift ;;
|
||||||
|
--install-only) INSTALL_ONLY=1; shift ;;
|
||||||
|
--remove) REMOVE=1; shift ;;
|
||||||
|
-h|--help) usage; exit 0 ;;
|
||||||
|
*) die "unknown option: $1 (see --help)" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
find_opencode() {
|
||||||
|
OC="$(command -v opencode || true)"
|
||||||
|
if [ -z "$OC" ] && [ -x "$HOME/.opencode/bin/opencode" ]; then OC="$HOME/.opencode/bin/opencode"; fi
|
||||||
|
}
|
||||||
|
install_opencode() {
|
||||||
|
say "Installing opencode (official installer)"
|
||||||
|
curl -fsSL https://opencode.ai/install | bash
|
||||||
|
find_opencode
|
||||||
|
[ -n "$OC" ] || die "opencode didn't install; see the output above"
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ "$INSTALL_ONLY" = 1 ]; then
|
||||||
|
find_opencode
|
||||||
|
if [ -n "$OC" ]; then say "opencode is already installed ($OC)"; else install_opencode; fi
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# A terminal to ask on, even when this script arrived on stdin.
|
||||||
|
TTY=""
|
||||||
|
if [ -r /dev/tty ] && [ -w /dev/tty ] && (: </dev/tty) 2>/dev/null; then TTY=/dev/tty; fi
|
||||||
|
|
||||||
|
if [ -z "$URL" ]; then
|
||||||
|
[ -n "$TTY" ] || die "--url is required"
|
||||||
|
printf 'API address (e.g. https://llm-api.example.com): ' >"$TTY"; read -r URL <"$TTY"
|
||||||
|
fi
|
||||||
|
URL="${URL%/}"
|
||||||
|
case "$URL" in
|
||||||
|
https://*|http://*) ;;
|
||||||
|
*) die "--url should start with https:// (got '$URL')" ;;
|
||||||
|
esac
|
||||||
|
case "$URL" in */v1) ;; *) URL="$URL/v1" ;; esac
|
||||||
|
HOST="$(printf '%s' "$URL" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')"
|
||||||
|
SHORT="$(printf '%s' "${HOST%%.*}" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9-\n' '-')"
|
||||||
|
PROV="llmhost-$SHORT"
|
||||||
|
CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
|
||||||
|
CONF="$CONF_DIR/opencode.json"
|
||||||
|
KEYFILE="$CONF_DIR/$PROV.key"
|
||||||
|
AUTH="${XDG_DATA_HOME:-$HOME/.local/share}/opencode/auth.json"
|
||||||
|
|
||||||
|
# JSON edits need Python. On a Mac without the command line tools, /usr/bin/python3 is
|
||||||
|
# only a stub that pops up an installer, so don't call it there.
|
||||||
|
PY=""
|
||||||
|
if [ "$(uname -s)" = Darwin ] && [ "$(command -v python3 || true)" = /usr/bin/python3 ] \
|
||||||
|
&& ! xcode-select -p >/dev/null 2>&1; then
|
||||||
|
PY=""
|
||||||
|
elif command -v python3 >/dev/null 2>&1; then
|
||||||
|
PY="$(command -v python3)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ---- remove --------------------------------------------------------------------------
|
||||||
|
if [ "$REMOVE" = 1 ]; then
|
||||||
|
[ -n "$PY" ] || die "python3 is needed to edit $CONF; remove the \"$PROV\" provider from it by hand"
|
||||||
|
"$PY" - "$CONF" "$PROV" "$AUTH" <<'PYEOF'
|
||||||
|
import json, os, sys
|
||||||
|
conf, prov, auth = sys.argv[1:4]
|
||||||
|
try:
|
||||||
|
c = json.load(open(conf))
|
||||||
|
except (OSError, ValueError):
|
||||||
|
c = None
|
||||||
|
if isinstance(c, dict) and prov in (c.get("provider") or {}):
|
||||||
|
del c["provider"][prov]
|
||||||
|
if not c["provider"]:
|
||||||
|
del c["provider"]
|
||||||
|
if str(c.get("model", "")).startswith(prov + "/"):
|
||||||
|
del c["model"]
|
||||||
|
print(f"opencode's default model was {prov}; pick another with /models.")
|
||||||
|
tmp = conf + ".tmp"
|
||||||
|
with open(tmp, "w") as f:
|
||||||
|
json.dump(c, f, indent=2); f.write("\n")
|
||||||
|
os.replace(tmp, conf)
|
||||||
|
print(f"Removed the {prov} provider from {conf}.")
|
||||||
|
else:
|
||||||
|
print(f"No {prov} provider in {conf}.")
|
||||||
|
try:
|
||||||
|
a = json.load(open(auth))
|
||||||
|
if prov in a:
|
||||||
|
del a[prov]
|
||||||
|
json.dump(a, open(auth, "w"), indent=2)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
PYEOF
|
||||||
|
rm -f "$KEYFILE"
|
||||||
|
say "Done. opencode itself is still installed."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ---- the key, checked against the server ---------------------------------------------
|
||||||
|
if [ -z "$KEY" ]; then
|
||||||
|
[ -n "$TTY" ] || die "no API key: pass --key or set \$LLMHOST_API_KEY"
|
||||||
|
printf 'API key (hidden): ' >"$TTY"
|
||||||
|
stty -echo <"$TTY" 2>/dev/null || true
|
||||||
|
read -r KEY <"$TTY" || true
|
||||||
|
stty echo <"$TTY" 2>/dev/null || true
|
||||||
|
printf '\n' >"$TTY"
|
||||||
|
fi
|
||||||
|
KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
|
||||||
|
[ -n "$KEY" ] || die "no API key given"
|
||||||
|
|
||||||
|
say "Checking $URL"
|
||||||
|
TMP="$(mktemp)"; trap 'rm -f "$TMP"' EXIT
|
||||||
|
# The key goes to curl on stdin (as a header file), not on its command line.
|
||||||
|
CODE="$(printf 'Authorization: Bearer %s\n' "$KEY" | curl -sS -o "$TMP" -w '%{http_code}' \
|
||||||
|
--max-time 20 -H @- "$URL/models" 2>/dev/null || true)"
|
||||||
|
case "$CODE" in
|
||||||
|
200) ;;
|
||||||
|
401|403) die "the server rejected that API key" ;;
|
||||||
|
000|"") die "couldn't reach $URL" ;;
|
||||||
|
*) die "$URL/models answered HTTP $CODE; is that the llm-host API address?" ;;
|
||||||
|
esac
|
||||||
|
CTX=32768; REASONS=0
|
||||||
|
if [ -n "$PY" ]; then
|
||||||
|
read -r CTX REASONS <<EOF
|
||||||
|
$("$PY" -c 'import json,sys
|
||||||
|
d=(json.load(open(sys.argv[1])).get("data") or [{}])[0]
|
||||||
|
print(int(d.get("max_model_len") or 32768), 1 if d.get("reasoning") else 0)' "$TMP" 2>/dev/null || echo "32768 0")
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
say "Server OK"
|
||||||
|
|
||||||
|
# ---- opencode ------------------------------------------------------------------------
|
||||||
|
find_opencode
|
||||||
|
if [ -z "$OC" ]; then
|
||||||
|
if [ "$INSTALL" = 1 ]; then
|
||||||
|
install_opencode
|
||||||
|
else
|
||||||
|
warn "opencode isn't installed; configuring it anyway (--skip-install)"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
say "opencode is already installed ($OC)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ---- key file ------------------------------------------------------------------------
|
||||||
|
mkdir -p "$CONF_DIR"
|
||||||
|
( umask 077; printf '%s\n' "$KEY" >"$KEYFILE" )
|
||||||
|
chmod 600 "$KEYFILE"
|
||||||
|
say "Saved the key to $KEYFILE"
|
||||||
|
|
||||||
|
# ---- opencode.json -------------------------------------------------------------------
|
||||||
|
print_block() {
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
Add this provider to $1 by hand, under "provider", and set "model" if you want it as the default:
|
||||||
|
|
||||||
|
"$PROV": {
|
||||||
|
"npm": "@ai-sdk/openai-compatible",
|
||||||
|
"name": "LLMHost ($HOST)",
|
||||||
|
"options": { "baseURL": "$URL", "apiKey": "{file:$KEYFILE}" },
|
||||||
|
"models": { "default": { "name": "Default model ($HOST)", "tool_call": true,
|
||||||
|
"limit": { "context": $CTX, "output": $(( CTX / 2 < 65536 ? CTX / 2 : 65536 )) } } }
|
||||||
|
}
|
||||||
|
|
||||||
|
"model": "$PROV/default"
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
if [ -z "$PY" ]; then
|
||||||
|
warn "python3 isn't available, so opencode.json can't be edited automatically."
|
||||||
|
print_block "$CONF"; exit 0
|
||||||
|
fi
|
||||||
|
if [ ! -f "$CONF" ] && [ -f "$CONF_DIR/opencode.jsonc" ]; then
|
||||||
|
warn "$CONF_DIR/opencode.jsonc has comments that an automatic edit would lose."
|
||||||
|
print_block "$CONF_DIR/opencode.jsonc"; exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
CURRENT_MODEL="$("$PY" -c 'import json,sys
|
||||||
|
try: print(json.load(open(sys.argv[1])).get("model") or "")
|
||||||
|
except Exception: print("")' "$CONF")"
|
||||||
|
SET_DEFAULT=0
|
||||||
|
case "$DEFAULT" in
|
||||||
|
yes) SET_DEFAULT=1 ;;
|
||||||
|
no) SET_DEFAULT=0 ;;
|
||||||
|
ask)
|
||||||
|
if [ -z "$CURRENT_MODEL" ] || [ "${CURRENT_MODEL#$PROV/}" != "$CURRENT_MODEL" ]; then
|
||||||
|
SET_DEFAULT=1
|
||||||
|
elif [ -n "$TTY" ]; then
|
||||||
|
printf 'opencode currently starts on %s. Switch its default to this server? [y/N] ' "$CURRENT_MODEL" >"$TTY"
|
||||||
|
read -r ans <"$TTY" || ans=""
|
||||||
|
case "$ans" in y|Y|yes|YES) SET_DEFAULT=1 ;; esac
|
||||||
|
fi ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
"$PY" - "$CONF" "$PROV" "$HOST" "$URL" "$KEYFILE" "$CTX" "$REASONS" "$SET_DEFAULT" "$AUTH" <<'PYEOF'
|
||||||
|
import json, os, shutil, sys
|
||||||
|
conf, prov, host, url, keyfile, ctx, reasons, set_default, auth = sys.argv[1:10]
|
||||||
|
ctx = int(ctx)
|
||||||
|
c = {}
|
||||||
|
if os.path.exists(conf) and os.path.getsize(conf) > 0:
|
||||||
|
try:
|
||||||
|
c = json.load(open(conf))
|
||||||
|
except ValueError as e:
|
||||||
|
sys.exit(f"Error: {conf} isn't valid JSON ({e}); fix it, or move it aside and run this again")
|
||||||
|
if not isinstance(c, dict):
|
||||||
|
sys.exit(f"Error: {conf} isn't a JSON object")
|
||||||
|
backup = conf + ".before-llmhost"
|
||||||
|
if not os.path.exists(backup):
|
||||||
|
shutil.copy2(conf, backup)
|
||||||
|
print(f"Backed up {conf} to {backup}")
|
||||||
|
|
||||||
|
# The same entry as `llmhost opencode-config`: one model, `default`, which the server
|
||||||
|
# answers to whatever is loaded; and, for a thinking model, opencode's own effort menu
|
||||||
|
# switched off, since the effort is set on the dashboard and the server drops a client's.
|
||||||
|
entry = {"name": f"Default model ({host})", "tool_call": True,
|
||||||
|
"limit": {"context": ctx, "output": min(65536, ctx // 2)}}
|
||||||
|
if reasons == "1":
|
||||||
|
entry["reasoning"] = True
|
||||||
|
entry["variants"] = {lvl: {"disabled": True} for lvl in ("low", "medium", "high")}
|
||||||
|
c.setdefault("$schema", "https://opencode.ai/config.json")
|
||||||
|
c.setdefault("provider", {})[prov] = {
|
||||||
|
"npm": "@ai-sdk/openai-compatible",
|
||||||
|
"name": f"LLMHost ({host})",
|
||||||
|
"options": {"baseURL": url, "apiKey": "{file:" + keyfile + "}"},
|
||||||
|
"models": {"default": entry},
|
||||||
|
}
|
||||||
|
if set_default == "1":
|
||||||
|
c["model"] = f"{prov}/default"
|
||||||
|
os.makedirs(os.path.dirname(conf), exist_ok=True)
|
||||||
|
tmp = conf + ".tmp"
|
||||||
|
with open(tmp, "w") as f:
|
||||||
|
json.dump(c, f, indent=2); f.write("\n")
|
||||||
|
os.replace(tmp, conf)
|
||||||
|
print(f"Added the {prov} provider to {conf}" + (" and made it the default model" if set_default == "1" else ""))
|
||||||
|
|
||||||
|
# opencode caches a key it was given interactively, and that copy wins over the config;
|
||||||
|
# drop it so the key file is what's used.
|
||||||
|
try:
|
||||||
|
a = json.load(open(auth))
|
||||||
|
if prov in a:
|
||||||
|
del a[prov]
|
||||||
|
tmp = auth + ".tmp"
|
||||||
|
with open(tmp, "w") as f:
|
||||||
|
json.dump(a, f, indent=2)
|
||||||
|
os.chmod(tmp, 0o600)
|
||||||
|
os.replace(tmp, auth)
|
||||||
|
print(f"Dropped the key opencode had cached for {prov}")
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
PYEOF
|
||||||
|
|
||||||
|
# ---- check ---------------------------------------------------------------------------
|
||||||
|
if [ -n "$OC" ] && "$OC" models 2>/dev/null | grep -q "^$PROV/default\$"; then
|
||||||
|
say "${G}opencode sees $PROV/default${N}"
|
||||||
|
elif [ -n "$OC" ]; then
|
||||||
|
warn "opencode doesn't list $PROV/default yet; check $CONF"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
say "Done. Start opencode -- it shows the server as \"LLMHost ($HOST)\"."
|
||||||
|
if [ "$SET_DEFAULT" != 1 ]; then
|
||||||
|
echo " Your default model is unchanged; pick \"LLMHost ($HOST)\" with /models."
|
||||||
|
fi
|
||||||
|
case ":$PATH:" in
|
||||||
|
*":$HOME/.opencode/bin:"*) ;;
|
||||||
|
*) if [ "$OC" = "$HOME/.opencode/bin/opencode" ]; then
|
||||||
|
echo " Open a new terminal first (or run: export PATH=\$HOME/.opencode/bin:\$PATH)."
|
||||||
|
fi ;;
|
||||||
|
esac
|
||||||
|
echo " To take it out again: rerun this with --remove."
|
||||||
1
tests/fixtures/qr_golden.json
vendored
Normal file
1
tests/fixtures/qr_golden.json
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -40,7 +40,7 @@ def guard(paths, root):
|
||||||
paths.BIN_DIR = Path(root) / ".local/bin"
|
paths.BIN_DIR = Path(root) / ".local/bin"
|
||||||
paths.SHIM = paths.BIN_DIR / "llmhost"
|
paths.SHIM = paths.BIN_DIR / "llmhost"
|
||||||
paths.LOG_DIR = Path(root) / "logs"
|
paths.LOG_DIR = Path(root) / "logs"
|
||||||
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "BIN_DIR", "SHIM", "LOG_DIR"):
|
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "OIDC_SECRET_FILE", "NEWT_SECRET_FILE", "OTP_SECRET_FILE", "NEWT_DIR", "BIN_DIR", "SHIM", "LOG_DIR"):
|
||||||
value = str(getattr(paths, name))
|
value = str(getattr(paths, name))
|
||||||
if not value.startswith(root):
|
if not value.startswith(root):
|
||||||
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")
|
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")
|
||||||
|
|
|
||||||
|
|
@ -66,34 +66,27 @@ for t, kv in ((99.0, 10.0), (101.0, 40.0), (105.0, 72.5), (109.0, 55.0), (111.0,
|
||||||
s.history.append({"t": t, "kv": kv, "gen": None, "prompt": None, "ttft": None,
|
s.history.append({"t": t, "kv": kv, "gen": None, "prompt": None, "ttft": None,
|
||||||
"util": None, "temp": None, "power": None})
|
"util": None, "temp": None, "power": None})
|
||||||
point = {"t": 111.0, "kv": 90.0}
|
point = {"t": 111.0, "kv": 90.0}
|
||||||
gen_tps, prompt_tps = (None, None)
|
|
||||||
|
|
||||||
# exercise the real merge code by calling the block through a tiny shim
|
# The merge loop's own bookkeeping, around the real run_row/run_kv_peak it calls.
|
||||||
def merge(sampler, recent, point):
|
def merge(sampler, recent, point):
|
||||||
metrics = {"recent": recent}
|
for r in recent:
|
||||||
def run_rates(r):
|
|
||||||
dur, ttft = r.get("dur") or 0, r.get("ttft")
|
|
||||||
p = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
|
|
||||||
w = dur - ttft if (ttft is not None and dur > ttft) else dur
|
|
||||||
g = (r["gen"] / w) if (w and r.get("gen")) else None
|
|
||||||
return g, p
|
|
||||||
for r in metrics["recent"]:
|
|
||||||
key = (r.get("start"), r.get("end"))
|
key = (r.get("start"), r.get("end"))
|
||||||
if key in sampler._seen_runs or r.get("start") is None: continue
|
if key in sampler._seen_runs or r.get("start") is None: continue
|
||||||
sampler._seen_runs.add(key)
|
sampler._seen_runs.add(key)
|
||||||
window = [q["kv"] for q in sampler.history
|
window = [q["kv"] for q in sampler.history
|
||||||
if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]]
|
if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]]
|
||||||
g, p = run_rates(r)
|
sampler.runs.append(web.run_row(r, max(window) if window else point["kv"]))
|
||||||
sampler.runs.append({"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
|
|
||||||
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
|
|
||||||
"gen_tps": g, "prompt_tps": p,
|
|
||||||
"kv_peak_pct": max(window) if window else point["kv"],
|
|
||||||
"aborted": bool(r.get("aborted"))})
|
|
||||||
|
|
||||||
merge(s, [run], point)
|
merge(s, [run], point)
|
||||||
r = s.runs[-1]
|
r = s.runs[-1]
|
||||||
|
check("prompt seconds = time to first token", r["prompt_s"] == 2.0, r["prompt_s"])
|
||||||
|
check("generated seconds = what's left of the duration", r["gen_s"] == 8.0, r["gen_s"])
|
||||||
|
check("the two phases account for the whole run", r["prompt_s"] + r["gen_s"] == r["dur"], r)
|
||||||
check("prompt tok/s = prompt / ttft", abs(r["prompt_tps"] - 7667 / 2.0) < 1e-6, r["prompt_tps"])
|
check("prompt tok/s = prompt / ttft", abs(r["prompt_tps"] - 7667 / 2.0) < 1e-6, r["prompt_tps"])
|
||||||
check("gen tok/s excludes the prefill", abs(r["gen_tps"] - 200 / 8.0) < 1e-6, r["gen_tps"])
|
check("gen tok/s excludes the prefill", abs(r["gen_tps"] - 200 / 8.0) < 1e-6, r["gen_tps"])
|
||||||
|
check("each rate matches the seconds shown next to it",
|
||||||
|
abs(r["prompt_tps"] - r["prompt"] / r["prompt_s"]) < 1e-9
|
||||||
|
and abs(r["gen_tps"] - r["gen"] / r["gen_s"]) < 1e-9, r)
|
||||||
check("peak KV from the run's own window", r["kv_peak_pct"] == 72.5, r["kv_peak_pct"])
|
check("peak KV from the run's own window", r["kv_peak_pct"] == 72.5, r["kv_peak_pct"])
|
||||||
check("points outside the window ignored", r["kv_peak_pct"] != 90.0)
|
check("points outside the window ignored", r["kv_peak_pct"] != 90.0)
|
||||||
merge(s, [run], point)
|
merge(s, [run], point)
|
||||||
|
|
@ -104,8 +97,15 @@ s2 = S()
|
||||||
merge(s2, [{"start": 1.0, "end": 1.0, "dur": 0.0, "gen": 0, "prompt": 0, "ttft": None}], {"t": 1, "kv": None})
|
merge(s2, [{"start": 1.0, "end": 1.0, "dur": 0.0, "gen": 0, "prompt": 0, "ttft": None}], {"t": 1, "kv": None})
|
||||||
r2 = s2.runs[-1]
|
r2 = s2.runs[-1]
|
||||||
check("no rates, no crash", r2["gen_tps"] is None and r2["prompt_tps"] is None, r2)
|
check("no rates, no crash", r2["gen_tps"] is None and r2["prompt_tps"] is None, r2)
|
||||||
|
check("no seconds either, rather than a zero", r2["prompt_s"] is None and r2["gen_s"] is None, r2)
|
||||||
merge(s2, [{"start": 2.0, "end": 3.0, "dur": 1.0, "gen": 5, "prompt": 9, "ttft": 1.0}], {"t": 3, "kv": None})
|
merge(s2, [{"start": 2.0, "end": 3.0, "dur": 1.0, "gen": 5, "prompt": 9, "ttft": 1.0}], {"t": 3, "kv": None})
|
||||||
check("ttft == dur -> gen rate falls back to duration", s2.runs[-1]["gen_tps"] == 5.0, s2.runs[-1])
|
check("ttft == dur -> gen rate falls back to duration", s2.runs[-1]["gen_tps"] == 5.0, s2.runs[-1])
|
||||||
|
check("...and the generated seconds say so too", s2.runs[-1]["gen_s"] == 1.0, s2.runs[-1])
|
||||||
|
merge(s2, [{"start": 4.0, "end": 6.0, "dur": 2.0, "gen": 8, "prompt": 40, "ttft": None}], {"t": 6, "kv": None})
|
||||||
|
nos = s2.runs[-1]
|
||||||
|
check("a run that didn't stream has no prompt seconds", nos["prompt_s"] is None, nos)
|
||||||
|
check("...no prompt rate to go with them", nos["prompt_tps"] is None, nos)
|
||||||
|
check("...and its whole duration counts as generation", nos["gen_s"] == 2.0 and nos["gen_tps"] == 4.0, nos)
|
||||||
check("no KV history -> current value", s2.runs[-1]["kv_peak_pct"] is None)
|
check("no KV history -> current value", s2.runs[-1]["kv_peak_pct"] is None)
|
||||||
|
|
||||||
print("\n6. the broken-pipe traceback you saw collapses to one line")
|
print("\n6. the broken-pipe traceback you saw collapses to one line")
|
||||||
|
|
|
||||||
261
tests/test_dashboard_auth.py
Normal file
261
tests/test_dashboard_auth.py
Normal file
|
|
@ -0,0 +1,261 @@
|
||||||
|
"""Dashboard sign-in: API key mode, and OIDC against a fake provider, through the real handler."""
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import urllib.parse
|
||||||
|
from http.server import ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import harness
|
||||||
|
|
||||||
|
ROOT = harness.setup()
|
||||||
|
from llmhost import cli, paths
|
||||||
|
from llmhost.web import oidc as oidc_mod
|
||||||
|
from llmhost.web import server as web
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
ISSUER = "https://auth.example.test"
|
||||||
|
PUBLIC = "https://dash.example.test"
|
||||||
|
KEY = "sk-test"
|
||||||
|
|
||||||
|
|
||||||
|
def b64(obj):
|
||||||
|
return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()
|
||||||
|
|
||||||
|
|
||||||
|
class FakeProvider:
|
||||||
|
"""Discovery, token and userinfo endpoints. The test sets what the next token
|
||||||
|
response's claims and userinfo look like."""
|
||||||
|
def __init__(self):
|
||||||
|
self.claims = {}
|
||||||
|
self.userinfo = {}
|
||||||
|
self.challenges = {} # code -> code_challenge
|
||||||
|
self.token_calls = 0
|
||||||
|
|
||||||
|
def __call__(self, method, url, data=None, headers=None):
|
||||||
|
if url == ISSUER + "/.well-known/openid-configuration":
|
||||||
|
return 200, json.dumps({
|
||||||
|
"issuer": ISSUER, "authorization_endpoint": ISSUER + "/authorize",
|
||||||
|
"token_endpoint": ISSUER + "/token", "userinfo_endpoint": ISSUER + "/userinfo"}).encode()
|
||||||
|
if url == ISSUER + "/token":
|
||||||
|
self.token_calls += 1
|
||||||
|
form = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode()).items()}
|
||||||
|
want = "Basic " + base64.b64encode(b"llm-host:s3cret").decode()
|
||||||
|
if headers.get("Authorization") != want:
|
||||||
|
return 401, b'{"error": "invalid_client"}'
|
||||||
|
verifier = form.get("code_verifier", "")
|
||||||
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
||||||
|
if self.challenges.get(form.get("code")) != challenge:
|
||||||
|
return 400, b'{"error": "invalid_grant"}'
|
||||||
|
if form.get("redirect_uri") != PUBLIC + "/auth/callback":
|
||||||
|
return 400, b'{"error": "invalid_grant"}'
|
||||||
|
return 200, json.dumps({"id_token": f"h.{b64(self.claims)}.sig", "access_token": "at"}).encode()
|
||||||
|
if url == ISSUER + "/userinfo":
|
||||||
|
return 200, json.dumps(self.userinfo).encode()
|
||||||
|
return 404, b"{}"
|
||||||
|
|
||||||
|
|
||||||
|
class StubSampler:
|
||||||
|
def __init__(self):
|
||||||
|
self.resets = 0
|
||||||
|
|
||||||
|
def snapshot(self):
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
def reset_stats(self):
|
||||||
|
self.resets += 1
|
||||||
|
|
||||||
|
|
||||||
|
def serve(oidc):
|
||||||
|
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, oidc))
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
return srv
|
||||||
|
|
||||||
|
|
||||||
|
def req(srv, method, path, headers=None, body=None):
|
||||||
|
c = http.client.HTTPConnection("127.0.0.1", srv.server_address[1], timeout=5)
|
||||||
|
c.request(method, path, body=body, headers=headers or {})
|
||||||
|
r = c.getresponse()
|
||||||
|
data = r.read()
|
||||||
|
out = (r.status, dict((k.lower(), v) for k, v in r.getheaders()), data,
|
||||||
|
[v for k, v in r.getheaders() if k.lower() == "set-cookie"])
|
||||||
|
c.close()
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
PUB_HOST = {"Host": "dash.example.test"}
|
||||||
|
|
||||||
|
print("\n1. API key mode is unchanged")
|
||||||
|
srv = serve(None)
|
||||||
|
st, _, body, _ = req(srv, "GET", "/auth/config")
|
||||||
|
check("config reports key mode", st == 200 and json.loads(body)["mode"] == "key", body)
|
||||||
|
check("status without key -> 401", req(srv, "GET", "/api/status")[0] == 401)
|
||||||
|
check("status with key -> 200", req(srv, "GET", "/api/status", {"Authorization": f"Bearer {KEY}"})[0] == 200)
|
||||||
|
check("no /auth/login without OIDC", req(srv, "GET", "/auth/login")[0] == 404)
|
||||||
|
paths.save_config(harness.config())
|
||||||
|
check("/api/connect needs the key", req(srv, "GET", "/api/connect")[0] == 401)
|
||||||
|
st, h, body, _ = req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})
|
||||||
|
cx = json.loads(body)
|
||||||
|
check("/api/connect returns the key", st == 200 and cx["key"] == KEY, body[:200])
|
||||||
|
check("/api/connect isn't cached", h.get("cache-control") == "no-store", h)
|
||||||
|
blk = cx["opencode"]
|
||||||
|
check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk/openai-compatible", blk)
|
||||||
|
check("opencode block offers the one alias", list(blk["models"]) == [cx["model"]] == ["default"], blk["models"])
|
||||||
|
check("opencode block leaves the address to the page", "LABEL" in blk["name"] and "HOST" in blk["options"]["baseURL"], blk)
|
||||||
|
check("the key isn't inlined in the block", KEY not in json.dumps(blk))
|
||||||
|
check("one address before any tunnel: the LAN", len(cx["targets"]) == 1
|
||||||
|
and cx["targets"][0]["url"].endswith(f":{harness.config()['api_port']}"), cx["targets"])
|
||||||
|
check("with its opencode-install.sh command", "/opencode-install.sh)\" -- --url http://" in cx["targets"][0]["command"],
|
||||||
|
cx["targets"])
|
||||||
|
c2 = harness.config(); c2["newt"] = {"endpoint": "https://p.example.test", "id": "x", "api_url": "https://llm-api.example.test"}
|
||||||
|
paths.save_config(c2)
|
||||||
|
cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2])
|
||||||
|
check("tunnel, local dashboard: internet then LAN", [t["where"] for t in cx["targets"]]
|
||||||
|
== ["from the internet", "on your local network"] and cx["targets"][0]["url"] == "https://llm-api.example.test", cx["targets"])
|
||||||
|
c2["dashboard_public"] = True
|
||||||
|
paths.save_config(c2)
|
||||||
|
cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2])
|
||||||
|
check("public dashboard: the internet only", [t["url"] for t in cx["targets"]] == ["https://llm-api.example.test"], cx["targets"])
|
||||||
|
paths.save_config(harness.config())
|
||||||
|
R = web.raw_file_url
|
||||||
|
check("raw URL for a Gitea/Forgejo repo", R("https://git.example.com/pub/llm-host.git", "main", "f.sh")
|
||||||
|
== "https://git.example.com/pub/llm-host/raw/branch/main/f.sh")
|
||||||
|
check("raw URL for a GitHub repo", R("https://github.com/someone/llm-host", "dev", "f.sh")
|
||||||
|
== "https://raw.githubusercontent.com/someone/llm-host/dev/f.sh")
|
||||||
|
check("no raw URL for an ssh remote", R("git@github.com:someone/llm-host.git", "main", "f.sh") is None)
|
||||||
|
srv.shutdown()
|
||||||
|
|
||||||
|
print("\n2. OIDC mode refuses the key and unsigned visitors")
|
||||||
|
prov = FakeProvider()
|
||||||
|
conf = {"mode": "oidc", "issuer": ISSUER, "client_id": "llm-host", "public_url": PUBLIC,
|
||||||
|
"allowed_groups": ["llm-admins"], "allowed_users": ["friend"]}
|
||||||
|
o = oidc_mod.OIDC(conf, "s3cret", http=prov)
|
||||||
|
srv = serve(o)
|
||||||
|
st, _, body, _ = req(srv, "GET", "/auth/config", PUB_HOST)
|
||||||
|
check("config reports oidc, nobody signed in", json.loads(body) == {"mode": "oidc", "user": None, "name": None}, body)
|
||||||
|
check("status without session -> 401", req(srv, "GET", "/api/status", PUB_HOST)[0] == 401)
|
||||||
|
check("the dashboard doesn't serve the opencode installer", req(srv, "GET", "/opencode-install.sh", PUB_HOST)[0] == 404)
|
||||||
|
check("the API key no longer opens it", req(srv, "GET", "/api/status", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
|
||||||
|
st, h, _, _ = req(srv, "GET", "/", {"Host": "mybox.local:11340"})
|
||||||
|
check("a LAN name is sent to the public URL", st == 302 and h["location"] == PUBLIC + "/", h.get("location"))
|
||||||
|
st, h, _, _ = req(srv, "GET", "/auth/login", {"Host": "mybox.local:11340"})
|
||||||
|
check("login by a LAN name starts on the public URL", st == 302 and h["location"] == PUBLIC + "/auth/login")
|
||||||
|
try:
|
||||||
|
oidc_mod.OIDC({**conf, "allowed_groups": [], "allowed_users": []}, "x")
|
||||||
|
check("an allow list is required", False)
|
||||||
|
except ValueError:
|
||||||
|
check("an allow list is required", True)
|
||||||
|
|
||||||
|
|
||||||
|
def login(claims_over=None, userinfo=None, cookie_state=None, tamper_state=None):
|
||||||
|
"""Run /auth/login then /auth/callback. Returns (callback status, session cookie or None, body)."""
|
||||||
|
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
|
||||||
|
assert st == 302, st
|
||||||
|
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
|
||||||
|
code = "code-" + q["state"][:8]
|
||||||
|
prov.challenges[code] = q["code_challenge"]
|
||||||
|
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "iat": 1, "sub": "u1",
|
||||||
|
"nonce": q["nonce"], "preferred_username": "alice", **(claims_over or {})}
|
||||||
|
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "name": "Alice",
|
||||||
|
"groups": ["llm-admins"]} if userinfo is None else userinfo
|
||||||
|
state_cookie = cookies[0].split(";")[0]
|
||||||
|
if cookie_state is not None:
|
||||||
|
state_cookie = f"{oidc_mod.STATE_COOKIE}={cookie_state}"
|
||||||
|
st, h, body, cookies = req(srv, "GET", "/auth/callback?" + urllib.parse.urlencode(
|
||||||
|
{"code": code, "state": tamper_state or q["state"], "iss": ISSUER}), {**PUB_HOST, "Cookie": state_cookie})
|
||||||
|
sess = next((c.split(";")[0] for c in cookies if c.startswith(oidc_mod.SESSION_COOKIE + "=")), None)
|
||||||
|
return st, sess, body, q, h
|
||||||
|
|
||||||
|
|
||||||
|
print("\n3. the authorization request")
|
||||||
|
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
|
||||||
|
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
|
||||||
|
check("redirects to the provider", h["location"].startswith(ISSUER + "/authorize?"))
|
||||||
|
check("PKCE S256", q.get("code_challenge_method") == "S256" and len(q.get("code_challenge", "")) == 43)
|
||||||
|
check("redirect URI is the public callback", q.get("redirect_uri") == PUBLIC + "/auth/callback")
|
||||||
|
check("asks for groups", "groups" in q.get("scope", "").split())
|
||||||
|
check("state cookie is HttpOnly, Secure, Lax, scoped to /auth/",
|
||||||
|
all(a in cookies[0] for a in ("HttpOnly", "Secure", "SameSite=Lax", "Path=/auth/")), cookies)
|
||||||
|
|
||||||
|
print("\n4. a good sign-in")
|
||||||
|
st, sess, body, q, h = login()
|
||||||
|
check("callback -> 302 home", st == 302 and h["location"] == "/", (st, body))
|
||||||
|
check("session cookie set", sess is not None)
|
||||||
|
st, _, body, _ = req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})
|
||||||
|
check("status with session -> 200", st == 200, st)
|
||||||
|
st, _, body, _ = req(srv, "GET", "/auth/config", {**PUB_HOST, "Cookie": sess})
|
||||||
|
check("config names the user", json.loads(body)["user"] == "alice" and json.loads(body)["name"] == "Alice", body)
|
||||||
|
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess})
|
||||||
|
check("POST without Origin -> 403", st == 403, st)
|
||||||
|
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})
|
||||||
|
check("POST from another origin -> 403", st == 403, st)
|
||||||
|
st, _, _, _ = req(srv, "POST", "/api/stats/reset", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
|
||||||
|
check("POST from the dashboard's origin -> 200", st == 200, st)
|
||||||
|
check("/api/connect refused without a session", req(srv, "GET", "/api/connect", PUB_HOST)[0] == 401)
|
||||||
|
check("/api/connect refused for the key alone", req(srv, "GET", "/api/connect", {**PUB_HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
|
||||||
|
st, _, body, _ = req(srv, "GET", "/api/connect", {**PUB_HOST, "Cookie": sess})
|
||||||
|
check("signed in: /api/connect returns the key", st == 200 and json.loads(body)["key"] == KEY, body[:200])
|
||||||
|
check("only the session's hash is stored", sess.split("=", 1)[1] not in o.sessions)
|
||||||
|
|
||||||
|
print("\n5. sign-ins that must fail")
|
||||||
|
before = len(o.sessions)
|
||||||
|
st, sess2, body, *_ = login(cookie_state="someone-elses-state")
|
||||||
|
check("state cookie mismatch -> 403, no session", st == 403 and sess2 is None, st)
|
||||||
|
st, sess2, *_ = login(claims_over={"nonce": "wrong"})
|
||||||
|
check("wrong nonce -> 403", st == 403 and sess2 is None, st)
|
||||||
|
st, sess2, *_ = login(claims_over={"aud": "other-client"})
|
||||||
|
check("ID token for another client -> 403", st == 403 and sess2 is None, st)
|
||||||
|
st, sess2, *_ = login(claims_over={"iss": "https://evil.test"})
|
||||||
|
check("ID token from another issuer -> 403", st == 403 and sess2 is None, st)
|
||||||
|
st, sess2, *_ = login(claims_over={"exp": 1})
|
||||||
|
check("expired ID token -> 403", st == 403 and sess2 is None, st)
|
||||||
|
st, sess2, body, *_ = login(userinfo={"sub": "u1", "preferred_username": "stranger", "groups": ["users"]},
|
||||||
|
claims_over={"preferred_username": "stranger"})
|
||||||
|
check("not in an allowed group -> 403", st == 403 and sess2 is None and b"isn't allowed" in body, body[:200])
|
||||||
|
st, sess2, *_ = login(userinfo={"sub": "u1", "preferred_username": "friend", "groups": []},
|
||||||
|
claims_over={"preferred_username": "friend"})
|
||||||
|
check("an allowed username gets in without the group", st == 302 and sess2 is not None, st)
|
||||||
|
st, sess3, *_ = login(userinfo={"sub": "OTHER", "preferred_username": "x", "groups": ["llm-admins"]},
|
||||||
|
claims_over={"preferred_username": "stranger"})
|
||||||
|
check("userinfo for a different sub is ignored", st == 403 and sess3 is None, st)
|
||||||
|
st, _, _, _ = req(srv, "GET", "/auth/callback?error=access_denied&state=x", {**PUB_HOST, "Cookie": f"{oidc_mod.STATE_COOKIE}=x"})
|
||||||
|
check("provider error -> 403", st == 403, st)
|
||||||
|
check("no stray sessions from the failures", len(o.sessions) == before + 1, len(o.sessions))
|
||||||
|
|
||||||
|
# A state can be used once.
|
||||||
|
st, h, _, cookies = req(srv, "GET", "/auth/login", PUB_HOST)
|
||||||
|
q = {k: v[0] for k, v in urllib.parse.parse_qs(urllib.parse.urlsplit(h["location"]).query).items()}
|
||||||
|
prov.challenges["c1"] = q["code_challenge"]
|
||||||
|
prov.claims = {"iss": ISSUER, "aud": "llm-host", "exp": 9e9, "sub": "u1", "nonce": q["nonce"]}
|
||||||
|
prov.userinfo = {"sub": "u1", "preferred_username": "alice", "groups": ["llm-admins"]}
|
||||||
|
cb = "/auth/callback?" + urllib.parse.urlencode({"code": "c1", "state": q["state"]})
|
||||||
|
hdr = {**PUB_HOST, "Cookie": cookies[0].split(";")[0]}
|
||||||
|
check("first use of a state works", req(srv, "GET", cb, hdr)[0] == 302)
|
||||||
|
check("replaying it -> 403", req(srv, "GET", cb, hdr)[0] == 403)
|
||||||
|
|
||||||
|
print("\n6. sign-out")
|
||||||
|
st, sess, *_ = login()
|
||||||
|
check("logout from another origin -> 403", req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
|
||||||
|
st, _, _, cookies = req(srv, "POST", "/auth/logout", {**PUB_HOST, "Cookie": sess, "Origin": PUBLIC})
|
||||||
|
check("logout -> 200 and clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
|
||||||
|
check("the old cookie no longer works", req(srv, "GET", "/api/status", {**PUB_HOST, "Cookie": sess})[0] == 401)
|
||||||
|
srv.shutdown()
|
||||||
|
|
||||||
|
print("\n7. setup keeps the dashboard's sign-in setting")
|
||||||
|
carried = cli.carried_settings({"dashboard_auth": conf, "reasoning": {"m": "low"}}, {"m"})
|
||||||
|
check("dashboard_auth carried", carried.get("dashboard_auth") == conf, carried)
|
||||||
|
check("reasoning still carried", carried.get("reasoning") == {"m": "low"})
|
||||||
|
check("nothing invented when unset", "dashboard_auth" not in cli.carried_settings({}, set()))
|
||||||
|
|
||||||
|
print("\n8. the client secret is stored privately")
|
||||||
|
paths.save_secret(paths.OIDC_SECRET_FILE, "s3cret")
|
||||||
|
check("secret file is 0600", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
|
||||||
|
check("reads back", paths.oidc_secret() == "s3cret")
|
||||||
|
|
||||||
|
check.done(ROOT)
|
||||||
249
tests/test_newt.py
Normal file
249
tests/test_newt.py
Normal file
|
|
@ -0,0 +1,249 @@
|
||||||
|
"""The internet upgrades, against fake services: install-newt (API only, pinned download,
|
||||||
|
secrets kept out of config/output/argv), install-oidc, install-otp, expose-dashboard, and
|
||||||
|
their remove-* undo commands."""
|
||||||
|
import contextlib
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import harness
|
||||||
|
|
||||||
|
ROOT = harness.setup()
|
||||||
|
from llmhost import cli, newt, otp, paths, service
|
||||||
|
from llmhost.web import oidc
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
ISSUER = "https://auth.example.test"
|
||||||
|
NEWT_SECRET = "newt-site-secret-xyz"
|
||||||
|
OIDC_SECRET = "oidc-client-secret-xyz"
|
||||||
|
|
||||||
|
# -- fakes ------------------------------------------------------------------------------
|
||||||
|
calls = []
|
||||||
|
installed = set()
|
||||||
|
service.install = lambda n: (calls.append(("install", n)), installed.add(n))
|
||||||
|
service.uninstall = lambda n: (calls.append(("uninstall", n)), installed.discard(n))
|
||||||
|
service.restart = lambda n: calls.append(("restart", n)) or True
|
||||||
|
service.installed = lambda n: n in installed
|
||||||
|
service.state = lambda n: ("active", 1.0)
|
||||||
|
|
||||||
|
FAKE_BIN = b"\x7fELF fake newt"
|
||||||
|
newt.SHA256 = {k: hashlib.sha256(FAKE_BIN).hexdigest() for k in newt.SHA256}
|
||||||
|
fetches = []
|
||||||
|
newt._fetch = lambda url: (fetches.append(url), FAKE_BIN)[1]
|
||||||
|
|
||||||
|
oidc.OIDC._http = staticmethod(lambda m, url, data=None, headers=None: (200, json.dumps({
|
||||||
|
"issuer": ISSUER, "authorization_endpoint": ISSUER + "/a", "token_endpoint": ISSUER + "/t"}).encode()))
|
||||||
|
|
||||||
|
|
||||||
|
class TTY(io.StringIO):
|
||||||
|
def isatty(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def run(argv, env=None, tty_input=None):
|
||||||
|
"""Run the CLI. Without tty_input there's no terminal (missing values are errors, not
|
||||||
|
prompts); with it, stdin/stdout are a terminal and input() reads those lines."""
|
||||||
|
saved = {k: os.environ.get(k) for k in ("LLMHOST_NEWT_SECRET", "LLMHOST_OIDC_SECRET")}
|
||||||
|
for k in saved:
|
||||||
|
os.environ.pop(k, None)
|
||||||
|
os.environ.update(env or {})
|
||||||
|
out, code = (TTY() if tty_input is not None else io.StringIO()), 0
|
||||||
|
old_in = sys.stdin
|
||||||
|
sys.stdin = TTY("".join(l + "\n" for l in tty_input)) if tty_input is not None else io.StringIO()
|
||||||
|
try:
|
||||||
|
with contextlib.redirect_stdout(out):
|
||||||
|
cli.main(argv)
|
||||||
|
except SystemExit as e:
|
||||||
|
code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
|
||||||
|
if isinstance(e.code, str):
|
||||||
|
out.write(e.code)
|
||||||
|
finally:
|
||||||
|
sys.stdin = old_in
|
||||||
|
for k, v in saved.items():
|
||||||
|
os.environ.pop(k, None)
|
||||||
|
if v is not None:
|
||||||
|
os.environ[k] = v
|
||||||
|
return code, out.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
cfg = harness.config()
|
||||||
|
paths.save_config(cfg)
|
||||||
|
paths.api_key(create=True)
|
||||||
|
|
||||||
|
NEWT_ARGS = ["install-newt", "--api-url", "https://llm-api.example.test", "--endpoint", "https://pangolin.example.test",
|
||||||
|
"--newt-id", "site123"]
|
||||||
|
NEWT_CONF = {"endpoint": "https://pangolin.example.test", "id": "site123", "api_url": "https://llm-api.example.test"}
|
||||||
|
OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER,
|
||||||
|
"--client-id", "client-from-provider", "--allow-group", "llm-admins"]
|
||||||
|
|
||||||
|
print("\n1. a plain install doesn't include newt")
|
||||||
|
check("setup's services are model and web only", service.NAMES == ("model", "web"), service.NAMES)
|
||||||
|
check("newt is an optional service", "newt" in service.OPTIONAL)
|
||||||
|
|
||||||
|
print("\n2. the pinned download is checked")
|
||||||
|
real = dict(newt.SHA256)
|
||||||
|
newt.SHA256 = {k: "0" * 64 for k in real}
|
||||||
|
try:
|
||||||
|
newt.ensure_binary(lambda *_: None)
|
||||||
|
check("a bad checksum is refused", False)
|
||||||
|
except SystemExit as e:
|
||||||
|
check("a bad checksum is refused", "checksum" in str(e), e)
|
||||||
|
check("nothing installed after a bad checksum", not newt.binary().exists())
|
||||||
|
newt.SHA256 = real
|
||||||
|
check("good checksum installs", newt.ensure_binary(lambda *_: None) is True)
|
||||||
|
check("binary is executable", newt.binary().stat().st_mode & 0o111)
|
||||||
|
check("second call is a no-op", newt.ensure_binary(lambda *_: None) is False)
|
||||||
|
check("download URL is the pinned GitHub release",
|
||||||
|
fetches[-1].startswith(f"https://github.com/fosrl/newt/releases/download/{newt.VERSION}/newt_"), fetches)
|
||||||
|
|
||||||
|
print("\n3. install-newt: the API only")
|
||||||
|
print("\n3a. the client commands before the tunnel: the local network only")
|
||||||
|
code, out = run(["opencode-config"])
|
||||||
|
check("opencode-config: one command, the LAN address", code == 0 and out.count("opencode-install.sh") == 1
|
||||||
|
and f"--url http://{cli.default_host()}:{cfg['api_port']}" in out, out)
|
||||||
|
code, out = run(["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "x"],
|
||||||
|
{"LLMHOST_NEWT_SECRET": NEWT_SECRET})
|
||||||
|
check("the API's public URL is required", code != 0 and "--api-url" in out, out)
|
||||||
|
code, out = run(["install-newt", "--api-url", "https://pangolin.example.test", "--endpoint", "https://pangolin.example.test",
|
||||||
|
"--newt-id", "x"], {"LLMHOST_NEWT_SECRET": NEWT_SECRET})
|
||||||
|
check("API URL = Pangolin endpoint is refused", code != 0 and "can't be the same" in out, out)
|
||||||
|
code, out = run(NEWT_ARGS)
|
||||||
|
check("missing secret without a terminal -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out)
|
||||||
|
calls.clear()
|
||||||
|
code, out = run(NEWT_ARGS, {"LLMHOST_NEWT_SECRET": NEWT_SECRET})
|
||||||
|
c = paths.load_config()
|
||||||
|
check("succeeds", code == 0, out)
|
||||||
|
check("newt config saved, with the API's public URL", c.get("newt") == NEWT_CONF, c.get("newt"))
|
||||||
|
check("the resource is named by the API's host", f"llm-api.example.test -> http://" in out, out)
|
||||||
|
check("prints the opencode command for the public URL", "opencode-install.sh)\" -- --url https://llm-api.example.test" in out, out)
|
||||||
|
check("dashboard sign-in untouched", "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists())
|
||||||
|
check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls)
|
||||||
|
check("dashboard not restarted", ("restart", "web") not in calls, calls)
|
||||||
|
check("only the API resource is described", f":{c['api_port']}" in out and f":{c['web_port']}" not in out, out)
|
||||||
|
check("points to expose-dashboard for the rest", "expose-dashboard" in out and "install-oidc" in out, out)
|
||||||
|
check("secret saved 0600, not in config or output",
|
||||||
|
(paths.NEWT_SECRET_FILE.stat().st_mode & 0o777) == 0o600
|
||||||
|
and NEWT_SECRET not in paths.CONFIG_FILE.read_text() and NEWT_SECRET not in out)
|
||||||
|
code, out = run(["install-newt", "--newt-id", "site456"])
|
||||||
|
c = paths.load_config()
|
||||||
|
check("re-run keeps what it isn't given", code == 0 and c["newt"] == {**NEWT_CONF, "id": "site456"}
|
||||||
|
and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out)
|
||||||
|
code, out = run(["install-newt", "--api-url", "https://llm-api.example.test/v1/"])
|
||||||
|
check("a trailing /v1 is dropped", code == 0 and paths.load_config()["newt"]["api_url"] == "https://llm-api.example.test", out)
|
||||||
|
|
||||||
|
print("\n3b. tunnel up, dashboard local: both commands")
|
||||||
|
code, out = run(["opencode-config"])
|
||||||
|
check("opencode-config: internet first, then local", code == 0 and out.count("opencode-install.sh") == 2
|
||||||
|
and out.index("--url https://llm-api.example.test") < out.index(f"--url http://{cli.default_host()}"), out)
|
||||||
|
check("by hand: for the public URL", '"baseURL": "https://llm-api.example.test/v1"' in out, out)
|
||||||
|
code, out = run(["status"])
|
||||||
|
check("status: API URL and a local dashboard", "API at https://llm-api.example.test/v1" in out and "local network only" in out, out)
|
||||||
|
|
||||||
|
print("\n4. newt starts with its credentials in the environment, not its arguments")
|
||||||
|
seen = {}
|
||||||
|
real_execve = os.execve
|
||||||
|
os.execve = lambda exe, argv, env: seen.update(exe=exe, argv=argv, env=env)
|
||||||
|
newt.run()
|
||||||
|
os.execve = real_execve
|
||||||
|
check("no secret on the command line", seen["argv"] == [str(newt.binary())], seen["argv"])
|
||||||
|
check("endpoint, id and secret in env",
|
||||||
|
(seen["env"]["PANGOLIN_ENDPOINT"], seen["env"]["NEWT_ID"], seen["env"]["NEWT_SECRET"])
|
||||||
|
== ("https://pangolin.example.test", "site456", NEWT_SECRET))
|
||||||
|
|
||||||
|
print("\n5. expose-dashboard won't publish behind the API key alone without asking")
|
||||||
|
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"])
|
||||||
|
check("refused without a terminal or --force", code != 0 and "install-oidc" in out and "install-otp" in out, out)
|
||||||
|
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["n"])
|
||||||
|
check("refused when you say no", code != 0 and "Not published" in out, out)
|
||||||
|
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test", "--force"])
|
||||||
|
check("--force walks through it anyway", code == 0 and f":{paths.load_config()['web_port']}" in out
|
||||||
|
and "dash.example.test" in out, out)
|
||||||
|
c = paths.load_config()
|
||||||
|
check("records that the dashboard is public, not where", c.get("dashboard_public") is True
|
||||||
|
and "dash.example.test" not in json.dumps({k: v for k, v in c.items() if k != "dashboard_auth"}), c.get("dashboard_public"))
|
||||||
|
code, out = run(["opencode-config"])
|
||||||
|
check("dashboard public: only the internet command", code == 0 and out.count("opencode-install.sh") == 1
|
||||||
|
and "--url https://llm-api.example.test" in out and f"http://{cli.default_host()}" not in out.split("Or by hand")[0], out)
|
||||||
|
|
||||||
|
print("\n6. install-oidc")
|
||||||
|
code, out = run(OIDC_ARGS)
|
||||||
|
check("missing secret -> error", code != 0 and "LLMHOST_OIDC_SECRET" in out, out)
|
||||||
|
code, out = run([a for a in OIDC_ARGS if a not in ("--allow-group", "llm-admins")], {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
|
||||||
|
check("no allow list -> error", code != 0 and "allow" in out, out)
|
||||||
|
calls.clear()
|
||||||
|
code, out = run(OIDC_ARGS, {"LLMHOST_OIDC_SECRET": OIDC_SECRET})
|
||||||
|
c = paths.load_config()
|
||||||
|
check("succeeds", code == 0, out)
|
||||||
|
check("dashboard switched to OIDC", c["dashboard_auth"]["mode"] == "oidc" and c["dashboard_auth"]["client_id"] == "client-from-provider")
|
||||||
|
check("newt untouched", c["newt"]["id"] == "site456")
|
||||||
|
check("dashboard restarted", ("restart", "web") in calls, calls)
|
||||||
|
check("prints the redirect URI", "https://dash.example.test/auth/callback" in out, out)
|
||||||
|
check("secret 0600, not in config or output", (paths.OIDC_SECRET_FILE.stat().st_mode & 0o777) == 0o600
|
||||||
|
and OIDC_SECRET not in paths.CONFIG_FILE.read_text() and OIDC_SECRET not in out)
|
||||||
|
code, out = run(["expose-dashboard"])
|
||||||
|
check("expose-dashboard with OIDC: no question, URL from OIDC", code == 0 and "dash.example.test" in out
|
||||||
|
and "redirect URI" in out, out)
|
||||||
|
|
||||||
|
print("\n7. install-otp")
|
||||||
|
code, out = run(["install-otp"])
|
||||||
|
check("needs a terminal", code != 0 and "terminal" in out, out)
|
||||||
|
FIXED = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
|
||||||
|
otp.new_secret = lambda: FIXED
|
||||||
|
code, out = run(["install-otp"], tty_input=["000000", "000001", "000002"])
|
||||||
|
check("wrong codes -> not paired", code != 0 and not paths.OTP_SECRET_FILE.exists(), out)
|
||||||
|
calls.clear()
|
||||||
|
code, out = run(["install-otp"], tty_input=[otp.code_at(FIXED, time.time())])
|
||||||
|
check("right code -> paired", code == 0 and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
|
||||||
|
check("secret 0600", (paths.OTP_SECRET_FILE.stat().st_mode & 0o777) == 0o600)
|
||||||
|
check("showed a QR code and the manual key", "▀" in out and otp.grouped(FIXED) in out, out[:300])
|
||||||
|
check("says OIDC takes precedence while it's on", "remove-oidc" in out, out)
|
||||||
|
check("dashboard restarted", ("restart", "web") in calls)
|
||||||
|
code, out = run(["install-otp"], tty_input=["n"])
|
||||||
|
check("re-running asks before replacing", code != 0 and "kept" in out and paths.OTP_SECRET_FILE.read_text().strip() == FIXED, out)
|
||||||
|
code, out = run(["install-otp", "--show"], tty_input=[])
|
||||||
|
check("--show shows the existing pairing", code == 0 and otp.grouped(FIXED) in out, out[:200])
|
||||||
|
|
||||||
|
print("\n8. status and setup keep it all")
|
||||||
|
code, out = run(["status"])
|
||||||
|
check("status names the sign-in", "OIDC via " + ISSUER in out, out)
|
||||||
|
carried = cli.carried_settings(paths.load_config(), set())
|
||||||
|
check("newt and dashboard_auth carried", "newt" in carried and "dashboard_auth" in carried, carried.keys())
|
||||||
|
|
||||||
|
print("\n9. remove-oidc, then expose-dashboard with codes")
|
||||||
|
code, out = run(["remove-oidc"])
|
||||||
|
c = paths.load_config()
|
||||||
|
check("OIDC off, secret deleted", code == 0 and "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists(), out)
|
||||||
|
check("says codes work again", "authenticator code" in out, out)
|
||||||
|
code, out = run(["status"])
|
||||||
|
check("status: key or code", "API key or authenticator code" in out, out)
|
||||||
|
code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test"], tty_input=["y", ""])
|
||||||
|
c = paths.load_config()
|
||||||
|
check("offers to turn the key off for the dashboard", code == 0 and c.get("dashboard_key_login") is False, out)
|
||||||
|
code, out = run(["status"])
|
||||||
|
check("status: codes only", "sign-in authenticator code" in out, out)
|
||||||
|
check("setup keeps the key switched off", cli.carried_settings(c, set()).get("dashboard_key_login") is False)
|
||||||
|
|
||||||
|
print("\n10. remove-otp and remove-newt")
|
||||||
|
code, out = run(["remove-otp"])
|
||||||
|
c = paths.load_config()
|
||||||
|
check("unpaired, key back on", code == 0 and not paths.OTP_SECRET_FILE.exists() and "dashboard_key_login" not in c, out)
|
||||||
|
calls.clear()
|
||||||
|
code, out = run(["remove-newt"])
|
||||||
|
c = paths.load_config()
|
||||||
|
check("newt removed", code == 0 and ("uninstall", "newt") in calls and "newt" not in c
|
||||||
|
and not paths.NEWT_SECRET_FILE.exists() and not newt.binary().exists(), out)
|
||||||
|
check("and the dashboard no longer counts as public", "dashboard_public" not in c)
|
||||||
|
check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models"))
|
||||||
|
code, out = run(["expose-dashboard"])
|
||||||
|
check("expose-dashboard needs newt first", code != 0 and "install-newt" in out, out)
|
||||||
|
code, out = run(["remove-newt"])
|
||||||
|
check("running it again is harmless", code == 0 and "wasn't installed" in out, out)
|
||||||
|
|
||||||
|
check.done(ROOT)
|
||||||
|
|
@ -47,21 +47,21 @@ check("limits come from the loaded model",
|
||||||
check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"])
|
check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"])
|
||||||
|
|
||||||
print("\n2. local + remote side by side")
|
print("\n2. local + remote side by side")
|
||||||
rp, rb = remote("popos.local")
|
rp, rb = remote("mybox.local")
|
||||||
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
||||||
st, path, prov, authcl = opencode.configure(CFG)
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
d = load()
|
d = load()
|
||||||
check("remote id is llmhost-popos", rp == "llmhost-popos", rp)
|
check("remote id is llmhost-mybox", rp == "llmhost-mybox", rp)
|
||||||
check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"])
|
check('remote name is "LLMHost (mybox.local)"', rb["name"] == "LLMHost (mybox.local)", rb["name"])
|
||||||
check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"]))
|
check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"]))
|
||||||
check("remote label names no model (it would go stale)",
|
check("remote label names no model (it would go stale)",
|
||||||
rb["models"]["default"]["name"] == "Default model (popos.local)", rb["models"]["default"]["name"])
|
rb["models"]["default"]["name"] == "Default model (mybox.local)", rb["models"]["default"]["name"])
|
||||||
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"]))
|
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-mybox"], sorted(d["provider"]))
|
||||||
check("remote untouched", d["provider"][rp] == rb)
|
check("remote untouched", d["provider"][rp] == rb)
|
||||||
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
|
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
|
||||||
|
|
||||||
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
|
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
|
||||||
_, rb2 = remote("popos.local", prov="llmhost")
|
_, rb2 = remote("mybox.local", prov="llmhost")
|
||||||
reset({"provider": {"llmhost": rb2}})
|
reset({"provider": {"llmhost": rb2}})
|
||||||
st, path, prov, authcl = opencode.configure(CFG)
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
d = load()
|
d = load()
|
||||||
|
|
@ -83,7 +83,7 @@ check("a stale default makes it an update", st == "updated", st)
|
||||||
check("and it is migrated", load()["model"] == "mymac/default", load().get("model"))
|
check("and it is migrated", load()["model"] == "mymac/default", load().get("model"))
|
||||||
|
|
||||||
print("\n5. uninstall: remove local, keep remote, repoint model")
|
print("\n5. uninstall: remove local, keep remote, repoint model")
|
||||||
rp, rb = remote("popos.local")
|
rp, rb = remote("mybox.local")
|
||||||
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"})
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"})
|
||||||
st, path, removed, new_model = opencode.remove(local=True)
|
st, path, removed, new_model = opencode.remove(local=True)
|
||||||
d = load()
|
d = load()
|
||||||
|
|
@ -108,13 +108,13 @@ check("remote still there", list(load()["provider"]) == [rp])
|
||||||
|
|
||||||
print("\n7. retiring a remote server (gap 3)")
|
print("\n7. retiring a remote server (gap 3)")
|
||||||
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
||||||
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
|
st, path, removed, new_model = opencode.remove(local=False, host="mybox.local")
|
||||||
d = load()
|
d = load()
|
||||||
check("removed the remote", removed == [rp], removed)
|
check("removed the remote", removed == [rp], removed)
|
||||||
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
|
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
|
||||||
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
|
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
|
||||||
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
|
||||||
st, path, removed, _ = opencode.remove(local=False, host="popos")
|
st, path, removed, _ = opencode.remove(local=False, host="mybox")
|
||||||
check("short hostname also matches", removed == [rp], removed)
|
check("short hostname also matches", removed == [rp], removed)
|
||||||
|
|
||||||
print("\n8. --all drops the model key when nothing is left")
|
print("\n8. --all drops the model key when nothing is left")
|
||||||
|
|
@ -126,15 +126,15 @@ check("model key dropped", "model" not in d and new_model is None, d)
|
||||||
check("provider key dropped", "provider" not in d, d)
|
check("provider key dropped", "provider" not in d, d)
|
||||||
|
|
||||||
print("\n9. foreign providers are never touched")
|
print("\n9. foreign providers are never touched")
|
||||||
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (popos)",
|
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (mybox)",
|
||||||
"options": {"baseURL": "http://popos.local:1134/v1", "apiKey": "{file:~/.config/opencode/popos-vllm.key}"},
|
"options": {"baseURL": "http://mybox.local:1134/v1", "apiKey": "{file:~/.config/opencode/mybox-vllm.key}"},
|
||||||
"models": {"x": {"name": "x"}}}
|
"models": {"x": {"name": "x"}}}
|
||||||
reset({"provider": {"popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "popos-vllm/x"})
|
reset({"provider": {"mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "mybox-vllm/x"})
|
||||||
st, path, removed, new_model = opencode.remove(local=True)
|
st, path, removed, new_model = opencode.remove(local=True)
|
||||||
d = load()
|
d = load()
|
||||||
check("only ours removed", removed == ["llmhost"], removed)
|
check("only ours removed", removed == ["llmhost"], removed)
|
||||||
check("foreign intact", d["provider"]["popos-vllm"] == foreign)
|
check("foreign intact", d["provider"]["mybox-vllm"] == foreign)
|
||||||
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
|
check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model"))
|
||||||
st, path, removed, _ = opencode.remove(local=False, every=True)
|
st, path, removed, _ = opencode.remove(local=False, every=True)
|
||||||
check("--all skips foreign", removed == [], removed)
|
check("--all skips foreign", removed == [], removed)
|
||||||
|
|
||||||
|
|
@ -165,15 +165,15 @@ st, path, prov, authcl = opencode.configure(CFG)
|
||||||
check("still installs", prov == "llmhost" and st == "added", (prov, st))
|
check("still installs", prov == "llmhost" and st == "added", (prov, st))
|
||||||
|
|
||||||
print("\n13. --host must not take a foreign provider on the same host (regression)")
|
print("\n13. --host must not take a foreign provider on the same host (regression)")
|
||||||
rp, rb = remote("popos.local")
|
rp, rb = remote("mybox.local")
|
||||||
reset({"provider": {rp: rb, "popos-vllm": foreign, "llmhost": opencode.local_block(CFG)},
|
reset({"provider": {rp: rb, "mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)},
|
||||||
"model": "popos-vllm/x"})
|
"model": "mybox-vllm/x"})
|
||||||
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
|
st, path, removed, new_model = opencode.remove(local=False, host="mybox.local")
|
||||||
d = load()
|
d = load()
|
||||||
check("removed only ours", removed == [rp], removed)
|
check("removed only ours", removed == [rp], removed)
|
||||||
check("foreign on same host survives", "popos-vllm" in d["provider"])
|
check("foreign on same host survives", "mybox-vllm" in d["provider"])
|
||||||
check("local survives", "llmhost" in d["provider"])
|
check("local survives", "llmhost" in d["provider"])
|
||||||
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
|
check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model"))
|
||||||
|
|
||||||
print("\n14. a stale cached key is cleared on configure")
|
print("\n14. a stale cached key is cleared on configure")
|
||||||
def put_auth(d, mode=0o600):
|
def put_auth(d, mode=0o600):
|
||||||
|
|
@ -212,12 +212,12 @@ check("left verbatim", f.read_text() == "{ not json")
|
||||||
check("reported nothing cleared", authcl is False, authcl)
|
check("reported nothing cleared", authcl is False, authcl)
|
||||||
|
|
||||||
print("\n17. remove() takes the cached key with the provider")
|
print("\n17. remove() takes the cached key with the provider")
|
||||||
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-popos": remote("popos.local")[1]}})
|
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-mybox": remote("mybox.local")[1]}})
|
||||||
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-popos": {"type": "api", "key": "sk-B"}})
|
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-mybox": {"type": "api", "key": "sk-B"}})
|
||||||
st, path, removed, _ = opencode.remove(local=True)
|
st, path, removed, _ = opencode.remove(local=True)
|
||||||
a = get_auth()
|
a = get_auth()
|
||||||
check("local cred cleared", "llmhost" not in a, a)
|
check("local cred cleared", "llmhost" not in a, a)
|
||||||
check("remote cred kept", a.get("llmhost-popos") == {"type": "api", "key": "sk-B"}, a)
|
check("remote cred kept", a.get("llmhost-mybox") == {"type": "api", "key": "sk-B"}, a)
|
||||||
|
|
||||||
print("\n18. purge --keep-key keeps the API key through a purge")
|
print("\n18. purge --keep-key keeps the API key through a purge")
|
||||||
from llmhost import cli
|
from llmhost import cli
|
||||||
|
|
@ -276,9 +276,9 @@ print("\n21. sync() never wires opencode up on its own")
|
||||||
reset()
|
reset()
|
||||||
check("no config file -> no-op", opencode.sync(CFG) is None)
|
check("no config file -> no-op", opencode.sync(CFG) is None)
|
||||||
check("still no config file", not opencode.config_file().exists())
|
check("still no config file", not opencode.config_file().exists())
|
||||||
reset({"provider": {"popos-vllm": foreign}, "model": "popos-vllm/x"})
|
reset({"provider": {"mybox-vllm": foreign}, "model": "mybox-vllm/x"})
|
||||||
check("no local block -> no-op", opencode.sync(CFG) is None)
|
check("no local block -> no-op", opencode.sync(CFG) is None)
|
||||||
check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign})
|
check("foreign provider untouched", load()["provider"] == {"mybox-vllm": foreign})
|
||||||
reset({"provider": {"mymac": opencode.local_block(CFG)}})
|
reset({"provider": {"mymac": opencode.local_block(CFG)}})
|
||||||
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
|
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
|
||||||
|
|
||||||
|
|
@ -286,8 +286,8 @@ check.section("22. a default naming a specific model is migrated to the alias")
|
||||||
for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"),
|
for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"),
|
||||||
("llmhost/ornith-1.5-9b", "llmhost/default"),
|
("llmhost/ornith-1.5-9b", "llmhost/default"),
|
||||||
("llmhost/default", "llmhost/default"),
|
("llmhost/default", "llmhost/default"),
|
||||||
("popos-vllm/qwen3.8-27b", "popos-vllm/qwen3.8-27b"),
|
("mybox-vllm/qwen3.8-27b", "mybox-vllm/qwen3.8-27b"),
|
||||||
("llmhost-popos/qwen3.8-27b", "llmhost-popos/qwen3.8-27b")):
|
("llmhost-mybox/qwen3.8-27b", "llmhost-mybox/qwen3.8-27b")):
|
||||||
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model})
|
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model})
|
||||||
opencode.configure(CFG)
|
opencode.configure(CFG)
|
||||||
got = load().get("model")
|
got = load().get("model")
|
||||||
|
|
@ -301,10 +301,10 @@ import argparse, io, contextlib
|
||||||
cli._service_check = lambda: CFG
|
cli._service_check = lambda: CFG
|
||||||
buf = io.StringIO()
|
buf = io.StringIO()
|
||||||
with contextlib.redirect_stdout(buf):
|
with contextlib.redirect_stdout(buf):
|
||||||
cli.cmd_opencode(argparse.Namespace(host="popos.local", provider=None, json=True))
|
cli.cmd_opencode(argparse.Namespace(host="mybox.local", provider=None, json=True))
|
||||||
snip = json.loads(buf.getvalue())
|
snip = json.loads(buf.getvalue())
|
||||||
prov_id, block = next(iter(snip["provider"].items()))
|
prov_id, block = next(iter(snip["provider"].items()))
|
||||||
check("provider named after the host", prov_id == "llmhost-popos", prov_id)
|
check("provider named after the host", prov_id == "llmhost-mybox", prov_id)
|
||||||
check("model is <provider>/<an entry in the block>",
|
check("model is <provider>/<an entry in the block>",
|
||||||
snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"],
|
snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"],
|
||||||
(snip["model"], list(block["models"])))
|
(snip["model"], list(block["models"])))
|
||||||
|
|
@ -313,7 +313,7 @@ check.section("24. the block never offers a reasoning chooser of its own")
|
||||||
check("opencode's whole menu is switched off",
|
check("opencode's whole menu is switched off",
|
||||||
opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")},
|
opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")},
|
||||||
opencode.effort_variants())
|
opencode.effort_variants())
|
||||||
q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local")
|
q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "mybox.local", "k", "mybox.local")
|
||||||
ent = q["models"]["default"]
|
ent = q["models"]["default"]
|
||||||
check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent)
|
check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent)
|
||||||
check("but every effort level is disabled",
|
check("but every effort level is disabled",
|
||||||
|
|
@ -322,9 +322,15 @@ check("no variant carries a reasoningEffort to send",
|
||||||
not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"])
|
not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"])
|
||||||
check("the model levels from the catalog are not offered either",
|
check("the model levels from the catalog are not offered either",
|
||||||
not ({"xhigh"} & set(ent["variants"])), ent["variants"])
|
not ({"xhigh"} & set(ent["variants"])), ent["variants"])
|
||||||
nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local")
|
nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "mybox.local", "k", "mybox.local")
|
||||||
check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"])
|
check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"])
|
||||||
check("one entry only, named for the alias, so the client can't pick a model either",
|
check("one entry only, named for the alias, so the client can't pick a model either",
|
||||||
list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"]))
|
list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"]))
|
||||||
|
|
||||||
|
print("\nthe command handed to other machines")
|
||||||
|
cmd = opencode.remote_command("http://mybox.local:1134")
|
||||||
|
check("fetches opencode-install.sh from a repo and passes the URL",
|
||||||
|
cmd.startswith('/bin/bash -c "$(curl -fsSL https://') and '/opencode-install.sh)" -- --url http://mybox.local:1134' in cmd, cmd)
|
||||||
|
check("the script it names is in this repo", (harness.REPO / "opencode-install.sh").exists())
|
||||||
|
|
||||||
check.done(ROOT)
|
check.done(ROOT)
|
||||||
|
|
|
||||||
195
tests/test_opencode_install.py
Normal file
195
tests/test_opencode_install.py
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
"""opencode-install.sh against a fake llm-host API, in a throwaway HOME: new and existing
|
||||||
|
opencode configs, the default-model choice, the cached-key cleanup, --remove, and the
|
||||||
|
official installer stood in for by a curl wrapper."""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import harness
|
||||||
|
|
||||||
|
ROOT = harness.setup()
|
||||||
|
from llmhost import paths
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
SCRIPT = harness.REPO / "opencode-install.sh"
|
||||||
|
KEY = "sk-test-key-for-the-installer"
|
||||||
|
STATE = {"reasoning": True}
|
||||||
|
|
||||||
|
|
||||||
|
class API(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
if self.headers.get("Authorization") != f"Bearer {KEY}":
|
||||||
|
self.send_response(401); self.end_headers(); return
|
||||||
|
if self.path != "/v1/models":
|
||||||
|
self.send_response(404); self.end_headers(); return
|
||||||
|
body = json.dumps({"object": "list", "data": [{"id": "some-model", "max_model_len": 131072,
|
||||||
|
"reasoning": STATE["reasoning"]}]}).encode()
|
||||||
|
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
|
||||||
|
srv = ThreadingHTTPServer(("127.0.0.1", 0), API)
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
URL = f"http://127.0.0.1:{srv.server_address[1]}"
|
||||||
|
PROV = "llmhost-127" # first label of the host, as the CLI and dashboard name it
|
||||||
|
|
||||||
|
REAL_CURL = subprocess.run(["bash", "-c", "command -v curl"], capture_output=True, text=True).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def sandbox(with_opencode=True):
|
||||||
|
home = Path(tempfile.mkdtemp(dir=ROOT, prefix="home-"))
|
||||||
|
bin_dir = home / "fakebin"
|
||||||
|
bin_dir.mkdir()
|
||||||
|
# Stand-in for the official installer: drop an `opencode` into ~/.opencode/bin.
|
||||||
|
(bin_dir / "curl").write_text(f"""#!/bin/bash
|
||||||
|
for a in "$@"; do
|
||||||
|
if [ "$a" = "https://opencode.ai/install" ]; then
|
||||||
|
cat <<'EOF'
|
||||||
|
mkdir -p "$HOME/.opencode/bin"
|
||||||
|
cp "$FAKE_OPENCODE" "$HOME/.opencode/bin/opencode"
|
||||||
|
echo "fake opencode installed"
|
||||||
|
EOF
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
exec {REAL_CURL} "$@"
|
||||||
|
""")
|
||||||
|
# A fake opencode whose `models` lists the providers' models from opencode.json.
|
||||||
|
fake_oc = home / "fake-opencode"
|
||||||
|
fake_oc.write_text(f"""#!/bin/bash
|
||||||
|
[ "$1" = models ] || exit 0
|
||||||
|
{sys.executable} -c 'import json,os
|
||||||
|
c=json.load(open(os.path.expanduser("~/.config/opencode/opencode.json")))
|
||||||
|
for p,b in (c.get("provider") or {{}}).items():
|
||||||
|
for m in b.get("models") or {{}}: print(p+"/"+m)'
|
||||||
|
""")
|
||||||
|
for f in (bin_dir / "curl", fake_oc):
|
||||||
|
f.chmod(0o755)
|
||||||
|
if with_opencode:
|
||||||
|
(bin_dir / "opencode").symlink_to(fake_oc)
|
||||||
|
return home, bin_dir, fake_oc
|
||||||
|
|
||||||
|
|
||||||
|
def run(home, bin_dir, fake_oc, *args, key=KEY):
|
||||||
|
env = {"HOME": str(home), "PATH": f"{bin_dir}:/usr/bin:/bin", "FAKE_OPENCODE": str(fake_oc)}
|
||||||
|
if key is not None:
|
||||||
|
env["LLMHOST_API_KEY"] = key
|
||||||
|
r = subprocess.run(["bash", str(SCRIPT), "--", *args], env=env, capture_output=True, text=True,
|
||||||
|
stdin=subprocess.DEVNULL, start_new_session=True, timeout=60) # no terminal
|
||||||
|
return r.returncode, r.stdout + r.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def conf(home):
|
||||||
|
return json.loads((home / ".config/opencode/opencode.json").read_text())
|
||||||
|
|
||||||
|
|
||||||
|
print("\n1. a new opencode user")
|
||||||
|
home, b, oc = sandbox(with_opencode=False)
|
||||||
|
code, out = run(home, b, oc, "--url", URL)
|
||||||
|
check("succeeds", code == 0, out)
|
||||||
|
check("installs opencode through the official installer", "fake opencode installed" in out
|
||||||
|
and (home / ".opencode/bin/opencode").exists(), out)
|
||||||
|
c = conf(home)
|
||||||
|
p = c["provider"][PROV]
|
||||||
|
check("provider added", p["options"]["baseURL"] == URL + "/v1", p)
|
||||||
|
check("key referenced by file, not inlined", p["options"]["apiKey"] == "{file:" + str(home / f".config/opencode/{PROV}.key") + "}"
|
||||||
|
and KEY not in json.dumps(c), p["options"])
|
||||||
|
check("made the default model", c.get("model") == f"{PROV}/default", c.get("model"))
|
||||||
|
check("schema set", c.get("$schema") == "https://opencode.ai/config.json")
|
||||||
|
check("context from the server", p["models"]["default"]["limit"] == {"context": 131072, "output": 65536})
|
||||||
|
check("thinking model: effort menu off", p["models"]["default"].get("variants", {}).get("high") == {"disabled": True})
|
||||||
|
kf = home / f".config/opencode/{PROV}.key"
|
||||||
|
check("key file saved 0600", kf.read_text().strip() == KEY and (kf.stat().st_mode & 0o777) == 0o600)
|
||||||
|
check("key not echoed", KEY not in out)
|
||||||
|
check("opencode sees it", f"opencode sees {PROV}/default" in out, out)
|
||||||
|
check("no backup for a config that didn't exist", not (home / ".config/opencode/opencode.json.before-llmhost").exists())
|
||||||
|
|
||||||
|
print("\n2. an existing opencode user")
|
||||||
|
home, b, oc = sandbox()
|
||||||
|
cd = home / ".config/opencode"; cd.mkdir(parents=True)
|
||||||
|
mine = {"$schema": "https://opencode.ai/config.json", "theme": "dark", "model": "anthropic/some-model",
|
||||||
|
"provider": {"other": {"npm": "x", "models": {"m": {}}}}}
|
||||||
|
(cd / "opencode.json").write_text(json.dumps(mine))
|
||||||
|
auth = home / ".local/share/opencode/auth.json"; auth.parent.mkdir(parents=True)
|
||||||
|
auth.write_text(json.dumps({PROV: {"type": "api", "key": "stale"}, "anthropic": {"type": "oauth"}}))
|
||||||
|
STATE["reasoning"] = False
|
||||||
|
code, out = run(home, b, oc, "--url", URL + "/v1/")
|
||||||
|
c = conf(home)
|
||||||
|
check("succeeds", code == 0, out)
|
||||||
|
check("didn't reinstall opencode", "already installed" in out and not (home / ".opencode").exists(), out)
|
||||||
|
check("other settings kept", c["theme"] == "dark" and "other" in c["provider"])
|
||||||
|
check("their default model kept (no terminal to ask on)", c["model"] == "anthropic/some-model", c["model"])
|
||||||
|
check("says how to pick it", "/models" in out, out)
|
||||||
|
check("original backed up", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
|
||||||
|
check("trailing /v1/ normalised", c["provider"][PROV]["options"]["baseURL"] == URL + "/v1")
|
||||||
|
check("non-thinking model: no variants", "variants" not in c["provider"][PROV]["models"]["default"])
|
||||||
|
a = json.loads(auth.read_text())
|
||||||
|
check("stale cached key dropped, others kept", PROV not in a and "anthropic" in a, a)
|
||||||
|
code, out = run(home, b, oc, "--url", URL, "--default")
|
||||||
|
check("--default switches the model", conf(home)["model"] == f"{PROV}/default")
|
||||||
|
check("backup not overwritten on a re-run", json.loads((cd / "opencode.json.before-llmhost").read_text()) == mine)
|
||||||
|
code, out = run(home, b, oc, "--url", URL)
|
||||||
|
check("a re-run keeps it the default", conf(home)["model"] == f"{PROV}/default")
|
||||||
|
STATE["reasoning"] = True
|
||||||
|
|
||||||
|
print("\n3. --remove")
|
||||||
|
code, out = run(home, b, oc, "--url", URL, "--remove", key=None)
|
||||||
|
c = conf(home)
|
||||||
|
check("succeeds without a key", code == 0, out)
|
||||||
|
check("provider gone, others kept", PROV not in c["provider"] and "other" in c["provider"], c)
|
||||||
|
check("model that pointed at it dropped", "model" not in c, c)
|
||||||
|
check("key file gone", not (cd / f"{PROV}.key").exists())
|
||||||
|
|
||||||
|
print("\n4. refusals")
|
||||||
|
home, b, oc = sandbox()
|
||||||
|
code, out = run(home, b, oc, "--url", URL, key="sk-wrong")
|
||||||
|
check("wrong key -> error", code != 0 and "rejected" in out, out)
|
||||||
|
check("nothing written after a wrong key", not (home / ".config/opencode").exists())
|
||||||
|
code, out = run(home, b, oc, "--url", URL, key=None)
|
||||||
|
check("no key and no terminal -> error", code != 0 and "no API key" in out, out)
|
||||||
|
code, out = run(home, b, oc, "--url", "ftp://x")
|
||||||
|
check("bad URL -> error", code != 0 and "https://" in out, out)
|
||||||
|
code, out = run(home, b, oc, "--url", "http://127.0.0.1:9")
|
||||||
|
check("unreachable -> error", code != 0 and "couldn't reach" in out, out)
|
||||||
|
cd = home / ".config/opencode"; cd.mkdir(parents=True)
|
||||||
|
(cd / "opencode.json").write_text("{ not json")
|
||||||
|
code, out = run(home, b, oc, "--url", URL)
|
||||||
|
check("broken JSON left alone", code != 0 and (cd / "opencode.json").read_text() == "{ not json", out)
|
||||||
|
(cd / "opencode.json").unlink()
|
||||||
|
(cd / "opencode.jsonc").write_text('{ // mine\n "theme": "dark" }')
|
||||||
|
code, out = run(home, b, oc, "--url", URL)
|
||||||
|
check("a .jsonc is never rewritten; the block is printed", code == 0 and "by hand" in out
|
||||||
|
and (cd / "opencode.jsonc").read_text().startswith("{ // mine") and not (cd / "opencode.json").exists(), out)
|
||||||
|
|
||||||
|
print("\n5. --install-only, which `llmhost setup` uses")
|
||||||
|
home, b, oc = sandbox(with_opencode=False)
|
||||||
|
code, out = run(home, b, oc, "--install-only", key=None)
|
||||||
|
check("installs without a URL or key", code == 0 and (home / ".opencode/bin/opencode").exists(), out)
|
||||||
|
check("touches no config", not (home / ".config/opencode").exists())
|
||||||
|
code, out = run(home, b, oc, "--install-only", key=None)
|
||||||
|
check("a second run finds it", code == 0 and "already installed" in out, out)
|
||||||
|
home, b, oc = sandbox(with_opencode=False)
|
||||||
|
env = {"HOME": str(home), "PATH": f"{b}:/usr/bin:/bin", "FAKE_OPENCODE": str(oc),
|
||||||
|
"LLMHOST_HOME": str(home / "lh"), "LLMHOST_CONFIG": str(home / "lhc"), "PYTHONPATH": str(harness.REPO)}
|
||||||
|
r = subprocess.run([sys.executable, "-c", "from llmhost import opencode; print('FOUND', opencode.install(lambda *_: None))"],
|
||||||
|
env=env, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, start_new_session=True)
|
||||||
|
check("llm-host's own opencode install goes through the script",
|
||||||
|
r.returncode == 0 and f"FOUND {home}/.opencode/bin/opencode" in r.stdout, r.stdout + r.stderr)
|
||||||
|
|
||||||
|
print("\n6. --help works when run as `bash -c`")
|
||||||
|
r = subprocess.run(["bash", "-c", SCRIPT.read_text(), "--", "--help"], capture_output=True, text=True)
|
||||||
|
check("prints usage", r.returncode == 0 and "--url" in r.stdout, r.stdout + r.stderr)
|
||||||
|
|
||||||
|
srv.shutdown()
|
||||||
|
check.done(ROOT)
|
||||||
145
tests/test_otp.py
Normal file
145
tests/test_otp.py
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
"""Authenticator codes: TOTP against RFC 6238, the verifier's replay and lockout rules, the
|
||||||
|
QR encoder against reference matrices, and code sign-in on the dashboard."""
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from http.server import ThreadingHTTPServer
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import harness
|
||||||
|
|
||||||
|
ROOT = harness.setup()
|
||||||
|
from llmhost import otp, paths, qr
|
||||||
|
from llmhost.web import server as web
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
print("\n1. TOTP matches RFC 6238 (SHA-1 vectors)")
|
||||||
|
RFC = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" # base32 of "12345678901234567890"
|
||||||
|
for t, want in ((59, "94287082"), (1111111109, "07081804"), (1111111111, "14050471"),
|
||||||
|
(1234567890, "89005924"), (2000000000, "69279037"), (20000000000, "65353130")):
|
||||||
|
check(f"t={t}", otp.code_at(RFC, t, digits=8) == want, otp.code_at(RFC, t, digits=8))
|
||||||
|
check("6 digits is the last six", otp.code_at(RFC, 59) == "287082")
|
||||||
|
check("new secrets are 160 bits of base32", len(otp.new_secret()) == 32 and otp.new_secret() != otp.new_secret())
|
||||||
|
uri = otp.pairing_uri("ABCDEFGH", "mybox.local")
|
||||||
|
check("pairing link", uri.startswith("otpauth://totp/llm-host:mybox.local?") and "secret=ABCDEFGH" in uri
|
||||||
|
and "issuer=llm-host" in uri and "period=30" in uri, uri)
|
||||||
|
check("grouped for typing", otp.grouped("ABCDEFGHIJ") == "ABCD EFGH IJ")
|
||||||
|
|
||||||
|
print("\n2. the verifier")
|
||||||
|
S = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"
|
||||||
|
now = [1_700_000_000.0]
|
||||||
|
v = otp.Verifier(S, clock=lambda: now[0])
|
||||||
|
code = otp.code_at(S, now[0])
|
||||||
|
check("current code accepted", v.check(code) == "ok")
|
||||||
|
check("same code again refused (replay)", v.check(code) == "wrong")
|
||||||
|
now[0] += 30
|
||||||
|
check("previous step's code refused once a later one was used", v.check(otp.code_at(S, now[0] - 30)) == "wrong")
|
||||||
|
check("drift: next step's code accepted", v.check(otp.code_at(S, now[0] + 30)) == "ok")
|
||||||
|
check("spaces and dashes tolerated", otp.matching_step(S, " ".join(otp.code_at(S, now[0])), now[0]) is not None)
|
||||||
|
check("wrong length refused", otp.matching_step(S, "12345", now[0]) is None)
|
||||||
|
v2 = otp.Verifier(S, clock=lambda: now[0])
|
||||||
|
for _ in range(otp.MAX_FAILURES):
|
||||||
|
v2.check("000000")
|
||||||
|
check(f"locked after {otp.MAX_FAILURES} wrong codes", v2.check(otp.code_at(S, now[0])) == "locked" and v2.locked_for() > 0)
|
||||||
|
now[0] += otp.FAIL_WINDOW + 1
|
||||||
|
check("unlocked after the window", v2.check(otp.code_at(S, now[0])) == "ok")
|
||||||
|
|
||||||
|
print("\n3. QR codes match reference matrices")
|
||||||
|
golden = json.loads((harness.FIXTURES / "qr_golden.json").read_text())
|
||||||
|
for text, g in golden.items():
|
||||||
|
q = qr.QR(text, mask=g["mask"])
|
||||||
|
rows = ["".join("1" if c else "0" for c in r) for r in q.m]
|
||||||
|
check(f"v{g['version']} ({len(text)} bytes)", q.version == g["version"] and rows == g["rows"])
|
||||||
|
q = qr.QR(otp.pairing_uri(otp.new_secret(), "a-rather-long-hostname.example.local"))
|
||||||
|
check("a pairing link fits", 1 <= q.version <= qr.MAX_VERSION and 0 <= q.mask <= 7)
|
||||||
|
check("terminal rendering: two modules per row, with a quiet zone", len(q.terminal()) == (q.size + 4 + 1) // 2)
|
||||||
|
try:
|
||||||
|
qr.QR("x" * 300)
|
||||||
|
check("too long is refused", False)
|
||||||
|
except ValueError:
|
||||||
|
check("too long is refused", True)
|
||||||
|
|
||||||
|
print("\n4. code sign-in on the dashboard")
|
||||||
|
KEY = "sk-test"
|
||||||
|
|
||||||
|
|
||||||
|
class StubSampler:
|
||||||
|
def snapshot(self):
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
def reset_stats(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def serve(**kw):
|
||||||
|
srv = ThreadingHTTPServer(("127.0.0.1", 0), web.make_handler(StubSampler(), KEY, **kw))
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
return srv
|
||||||
|
|
||||||
|
|
||||||
|
def req(srv, method, path, headers=None, body=None):
|
||||||
|
c = http.client.HTTPConnection("127.0.0.1", srv.server_address[1], timeout=5)
|
||||||
|
c.request(method, path, body=body, headers=headers or {})
|
||||||
|
r = c.getresponse()
|
||||||
|
data = r.read()
|
||||||
|
cookies = [v for k, v in r.getheaders() if k.lower() == "set-cookie"]
|
||||||
|
c.close()
|
||||||
|
return r.status, data, cookies
|
||||||
|
|
||||||
|
|
||||||
|
HOST = {"Host": "mybox.local:11340"}
|
||||||
|
SAME = {**HOST, "Origin": "http://mybox.local:11340", "Content-Type": "application/json"}
|
||||||
|
clock = [1_800_000_000.0]
|
||||||
|
verifier = otp.Verifier(S, clock=lambda: clock[0])
|
||||||
|
srv = serve(otp=verifier)
|
||||||
|
cfg = json.loads(req(srv, "GET", "/auth/config", HOST)[1])
|
||||||
|
check("config: key and codes", cfg == {"mode": "key", "key": True, "otp": True, "user": None, "name": None}, cfg)
|
||||||
|
check("key still works", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 200)
|
||||||
|
body = json.dumps({"code": otp.code_at(S, clock[0])})
|
||||||
|
check("code from another origin refused", req(srv, "POST", "/auth/otp", {**SAME, "Origin": "https://evil.test"}, body)[0] == 403)
|
||||||
|
check("code without an Origin refused", req(srv, "POST", "/auth/otp", HOST, body)[0] == 403)
|
||||||
|
st, data, cookies = req(srv, "POST", "/auth/otp", SAME, body)
|
||||||
|
sess = cookies[0].split(";")[0] if cookies else ""
|
||||||
|
check("right code -> session", st == 200 and sess.startswith("llmhost_session="), (st, data))
|
||||||
|
check("session cookie HttpOnly, Lax; not Secure over plain http",
|
||||||
|
"HttpOnly" in cookies[0] and "SameSite=Lax" in cookies[0] and "Secure" not in cookies[0], cookies)
|
||||||
|
check("session opens the API", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 200)
|
||||||
|
check("session POST from this page works", req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess})[0] == 200)
|
||||||
|
check("session POST from another origin refused",
|
||||||
|
req(srv, "POST", "/api/stats/reset", {**SAME, "Cookie": sess, "Origin": "https://evil.test"})[0] == 403)
|
||||||
|
cfg = json.loads(req(srv, "GET", "/auth/config", {**HOST, "Cookie": sess})[1])
|
||||||
|
check("config names the session", cfg["user"] == "authenticator", cfg)
|
||||||
|
check("same code can't be reused", req(srv, "POST", "/auth/otp", SAME, body)[0] == 401)
|
||||||
|
clock[0] += 60
|
||||||
|
st, _, cookies = req(srv, "POST", "/auth/otp", {**SAME, "X-Forwarded-Proto": "https"},
|
||||||
|
json.dumps({"code": otp.code_at(S, clock[0])}))
|
||||||
|
check("behind HTTPS the cookie is Secure", st == 200 and "Secure" in cookies[0], cookies)
|
||||||
|
for _ in range(otp.MAX_FAILURES):
|
||||||
|
req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "000000"}))
|
||||||
|
st, data, _ = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
|
||||||
|
check("too many wrong codes -> 429", st == 429 and json.loads(data)["retry_after"] > 0, (st, data))
|
||||||
|
st, _, cookies = req(srv, "POST", "/auth/logout", {**SAME, "Cookie": sess})
|
||||||
|
check("sign out clears the cookie", st == 200 and "Max-Age=0" in cookies[0], cookies)
|
||||||
|
check("old session no longer works", req(srv, "GET", "/api/status", {**HOST, "Cookie": sess})[0] == 401)
|
||||||
|
srv.shutdown()
|
||||||
|
|
||||||
|
print("\n5. key sign-in switched off for the dashboard")
|
||||||
|
v3 = otp.Verifier(S, clock=lambda: clock[0])
|
||||||
|
srv = serve(otp=v3, key_login=False)
|
||||||
|
check("config says so", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["key"] is False)
|
||||||
|
check("the key no longer opens the dashboard", req(srv, "GET", "/api/status", {**HOST, "Authorization": f"Bearer {KEY}"})[0] == 401)
|
||||||
|
st, _, cookies = req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": otp.code_at(S, clock[0] + 30)}))
|
||||||
|
check("a code still does", st == 200 and req(srv, "GET", "/api/status", {**HOST, "Cookie": cookies[0].split(";")[0]})[0] == 200)
|
||||||
|
srv.shutdown()
|
||||||
|
|
||||||
|
print("\n6. no codes without install-otp")
|
||||||
|
srv = serve()
|
||||||
|
check("config: no otp", json.loads(req(srv, "GET", "/auth/config", HOST)[1])["otp"] is False)
|
||||||
|
check("/auth/otp is 404", req(srv, "POST", "/auth/otp", SAME, json.dumps({"code": "123456"}))[0] == 404)
|
||||||
|
srv.shutdown()
|
||||||
|
|
||||||
|
check.done(ROOT)
|
||||||
|
|
@ -140,6 +140,8 @@ req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
|
||||||
with urllib.request.urlopen(req, timeout=10) as r:
|
with urllib.request.urlopen(req, timeout=10) as r:
|
||||||
d = json.loads(r.read())
|
d = json.loads(r.read())
|
||||||
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
|
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
|
||||||
|
check("reports context and whether it thinks", d["data"][0]["max_model_len"] == 262144
|
||||||
|
and d["data"][0]["reasoning"] is False, d)
|
||||||
|
|
||||||
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
|
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
|
||||||
VOUTER = 18233
|
VOUTER = 18233
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue