Compare commits

...

2 commits

Author SHA1 Message Date
b55ea07c96 Run sessions-web behind Authelia, configured only by env vars
Drop the app's own login (password hash, signed cookies, CSRF tokens, rate
limiting): Authelia via Caddy forward_auth is the login. The app refuses any
request without the Remote-User header (optionally limited to
SESSIONS_ALLOWED_USERS) and any cross-site POST (Sec-Fetch-Site / Origin).

The SSH key and the dev box host key now come from environment variables
printed by `sessions-ctl keygen`, so the container needs no secrets store or
mounts. Add compose.yaml so prod's panel can build and deploy it; remove the
Quadlet unit and the files it needed. README covers the panel deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac
2026-09-30 14:39:56 +00:00
ca66db3aeb Add sessions-ctl keygen to create prod's key on the dev box
keygen generates an ed25519 pair in RAM, writes the public half to
config.toml and authorized_keys (replacing the previous sessions-manager
line) and prints the web app's environment - dev host, port, user, pinned
host key and the private key as one base64 line - then deletes the private
key, so the pasted copy is the only one. Refuses to replace an existing key
without --rotate. Local only, never reachable over SSH.

Also make load_config() read CONFIG_PATH at call time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac
2026-09-30 14:39:56 +00:00
13 changed files with 419 additions and 339 deletions

View file

@ -8,13 +8,18 @@ model" before changing anything that touches the SSH boundary.
- `dev/` runs on the **dev box**: `sessions_ctl.py` (installed as - `dev/` runs on the **dev box**: `sessions_ctl.py` (installed as
`~/.local/bin/sessions-ctl`), systemd user units, `install.sh`. `~/.local/bin/sessions-ctl`), systemd user units, `install.sh`.
- `web/` runs on **prod** in a rootless Podman container: `app.py`, - `web/` runs on **prod** in a rootless Podman container: `app.py`,
`Containerfile`, Quadlet unit `sessions-web.container`. `Containerfile`. `compose.yaml` at the root is what prod's panel deploys.
Configured only through env vars; `sessions-ctl keygen` prints them.
## Stack and conventions ## Stack and conventions
- Python ≥ 3.11, **standard library only** on both sides. No pip install, so - Python ≥ 3.11, **standard library only** on both sides. No pip install, so
there's no supply chain to audit. Keep it that way unless there's a strong reason. there's no supply chain to audit. Keep it that way unless there's a strong reason.
- The web page has **no JavaScript**. Plain forms, POST, then a redirect. - The web page has **no JavaScript**. Plain forms, POST, then a redirect.
- `sessions-ctl` always prints exactly one JSON object; exit 0/1/2. - `sessions-ctl` prints exactly one JSON object (except `keygen`: KEY=VALUE
lines on stdout, human note on stderr); exit 0/1/2.
- The web app has no login: Authelia (Caddy forward_auth) in front of it is
the login. It must keep refusing requests without the auth header, and
refusing cross-site POSTs.
- The dev port for local work on the web app is **8470**, bound to 127.0.0.1. - The dev port for local work on the web app is **8470**, bound to 127.0.0.1.
Preview via `ssh -p 14922 -L 8470:localhost:8470 <dev box>`. Preview via `ssh -p 14922 -L 8470:localhost:8470 <dev box>`.
@ -22,8 +27,10 @@ model" before changing anything that touches the SSH boundary.
1. Nothing received over SSH reaches a shell or Claude. No "initial prompt" 1. Nothing received over SSH reaches a shell or Claude. No "initial prompt"
feature, no free-text arguments. New remote verbs need validation *and* a feature, no free-text arguments. New remote verbs need validation *and* a
test in `dev/tests/test_sessions_ctl.py`. test in `dev/tests/test_sessions_ctl.py`.
2. Local-only verbs (`delete`, `refresh-access`, `_launch`) stay out of 2. Local-only verbs (`delete`, `refresh-access`, `keygen`, `_launch`) stay out
`REMOTE_VERBS`. of `REMOTE_VERBS`.
6. The private key is never written to disk on the dev box outside a temp dir
in `XDG_RUNTIME_DIR` (RAM), which `keygen` removes.
3. `refresh-access` never writes an empty `from=`, and never touches lines 3. `refresh-access` never writes an empty `from=`, and never touches lines
other than the one ending in ` sessions-manager`. other than the one ending in ` sessions-manager`.
4. The session unit keeps `DBUS_SESSION_BUS_ADDRESS` pointed at nothing. 4. The session unit keeps `DBUS_SESSION_BUS_ADDRESS` pointed at nothing.
@ -38,5 +45,7 @@ python3 -m unittest discover -s web/tests
``` ```
To test end to end on the dev box, add a throwaway key with To test end to end on the dev box, add a throwaway key with
`from="127.0.0.1",restrict,command=".../sessions-ctl --remote" … sessions-selftest`, `from="127.0.0.1",restrict,command=".../sessions-ctl --remote" … sessions-selftest`,
run the container with `--network host` and `SESSIONS_DEV_HOST=127.0.0.1`, run the container with `--network host`, `SESSIONS_DEV_HOST=127.0.0.1` and the
then remove the key line again. key as `SESSIONS_SSH_KEY_B64`, send requests with a `Remote-User` header, then
remove the key line again. Never run the real `keygen` from an agent session:
its output is a private key and would end up in the transcript.

124
README.md
View file

@ -5,7 +5,7 @@ without SSHing in yourself. Each session runs `claude` with **Remote Control**,
you then talk to it from the Claude app or the "Open in Claude" link. you then talk to it from the Claude app or the "Open in Claude" link.
``` ```
phone/browser ──HTTPS──▶ prod: reverse proxy ──▶ sessions-web (container, 127.0.0.1:8470) phone/browser ──HTTPS──▶ prod: Caddy + Authelia ──▶ sessions-web (container, 127.0.0.1:<port>)
│ ssh, key locked to one command │ ssh, key locked to one command
▼ ▼
dev box: sessions-ctl --remote ──▶ systemd: claude-session@<name> dev box: sessions-ctl --remote ──▶ systemd: claude-session@<name>
@ -17,8 +17,8 @@ you then talk to it from the Claude app or the "Open in Claude" link.
|---|---|---| |---|---|---|
| [`dev/sessions_ctl.py`](dev/sessions_ctl.py) | dev box, `~/.local/bin/sessions-ctl` | CLI + SSH forced command. Stdlib Python ≥ 3.11 | | [`dev/sessions_ctl.py`](dev/sessions_ctl.py) | dev box, `~/.local/bin/sessions-ctl` | CLI + SSH forced command. Stdlib Python ≥ 3.11 |
| [`dev/systemd/`](dev/systemd) | dev box, `~/.config/systemd/user/` | one unit per session; hourly key-IP refresh | | [`dev/systemd/`](dev/systemd) | dev box, `~/.config/systemd/user/` | one unit per session; hourly key-IP refresh |
| [`web/app.py`](web/app.py) | prod, container | login page + session list; stdlib, no JS | | [`web/app.py`](web/app.py) | prod, container | session list + buttons; stdlib, no JS, no login of its own |
| [`web/sessions-web.container`](web/sessions-web.container) | prod, Quadlet | runs the container under systemd, restarts at boot | | [`compose.yaml`](compose.yaml) | prod, panel | how the panel builds and runs the container |
## Security model ## Security model
@ -43,13 +43,20 @@ from="<IP of reudy.net>",restrict,command="…/sessions-ctl --remote" ssh-ed2551
prompt". Instructions go through Remote Control, which is guarded by your prompt". Instructions go through Remote Control, which is guarded by your
claude.ai account, not by prod. So the worst a hijacked prod can do is start claude.ai account, not by prod. So the worst a hijacked prod can do is start
sessions up to `max_running`, or stop them. sessions up to `max_running`, or stop them.
- The web app: scrypt password hash, HMAC-signed `HttpOnly; Secure; - **The web app has no login of its own; Authelia is the login.** It serves
SameSite=Strict` cookie, CSRF token on every POST, 5 failed logins per IP / only requests carrying `Remote-User`, which Caddy's `forward_auth` sets from
20 overall per 15 min, strict CSP, no JavaScript. It pins the dev box host Authelia (overwriting anything the client sent). With the header missing it
key (`StrictHostKeyChecking yes`). answers 403. That's a tripwire in case the route ever loses forward_auth,
- The container is rootless, has a read-only root filesystem and drops all not the protection itself. `SESSIONS_ALLOWED_USERS` can narrow it to named
capabilities. It publishes only to `127.0.0.1`. Secrets are Podman secrets, users. Authelia's policy for the domain should be `two_factor`. It is by
not files beside the unit. default on prod.
- Cross-site POSTs are refused by checking `Sec-Fetch-Site`/`Origin`, so no
CSRF secret is needed. The page has a strict CSP and no JavaScript. The dev
box host key is pinned (`StrictHostKeyChecking yes`).
- The container is configured only by environment variables, including the
SSH key (one base64 line). At start it writes the key to a 0600 file on its
`/tmp` tmpfs. It runs rootless with a read-only root filesystem and all
capabilities dropped, published only on `127.0.0.1`.
- Every remote call is logged on the dev box: `journalctl -t sessions-ctl`. - Every remote call is logged on the dev box: `journalctl -t sessions-ctl`.
**Folder trust:** Claude Code asks "do you trust this folder?" on first launch **Folder trust:** Claude Code asks "do you trust this folder?" on first launch
@ -87,77 +94,74 @@ Claude Code field. If a Claude Code update breaks it, the session shows
```sh ```sh
git clone ssh://git@git.reudy.net:14922/reudy-net/sessions.git && cd sessions git clone ssh://git@git.reudy.net:14922/reudy-net/sessions.git && cd sessions
./dev/install.sh # idempotent; re-run after every pull ./dev/install.sh # idempotent; re-run after every pull
$EDITOR ~/.config/sessions/config.toml # [repos] allowlist + [ssh_access] $EDITOR ~/.config/sessions/config.toml # [repos] allowlist, [ssh_access] allow_from_host
./dev/install.sh # writes the authorized_keys line sessions-ctl keygen # add --rotate to replace an existing key
sessions-ctl health
``` ```
`keygen` makes the key pair prod uses. It generates it in RAM, writes the
public half to the config and `authorized_keys` (replacing the old
`sessions-manager` line), and prints the five environment variables for prod
to stdout, with a note on stderr. The private key is then deleted from this
box, so the printed copy is the only one. Paste it, then clear the terminal.
If it's lost, run `keygen --rotate` and paste again.
Requires linger (`sudo loginctl enable-linger agent`); `install.sh` warns if Requires linger (`sudo loginctl enable-linger agent`); `install.sh` warns if
it's off. it's off.
## Install: prod ## Deploy on prod (panel)
As the rootless user that will run the container. Replace `~/.ssh/<key>` with The repo root has a `compose.yaml`, so the panel can build and run it:
the private half of the key that is in the dev box's config.
1. **New app** in the panel from the Forgejo repo `reudy-net/sessions`, branch `main`.
2. **Environment**: paste the five lines `sessions-ctl keygen` printed. Optional:
`SESSIONS_ALLOWED_USERS=reudy`.
3. **Route**: e.g. `sessions.reudy.net` → service `web`, port `8470`, with
**Authelia on**. From the CLI:
`panelctl init sessions "sessions.reudy.net|127.0.0.1:18470||web:8470" true`
4. **Deploy.** The container log should say
`sessions-web on 0.0.0.0:8470 → agent@<dev box>:14922 …`.
5. Open `https://sessions.reudy.net`, sign in through Authelia, and you should
see the session list. An error there comes from the dev box (see
Troubleshooting).
**Reboots:** the container has `restart: unless-stopped`. Rootless Podman only
honours that at boot if the user's `podman-restart.service` is enabled
(`systemctl --user is-enabled podman-restart` as the panel user). That applies
to every panel app, so it belongs in the NixOS config.
### Without the panel
Any container runtime works. Put the five variables in a `chmod 600` env
file and run:
```sh ```sh
git clone ssh://git@git.reudy.net:14922/reudy-net/sessions.git && cd sessions podman build -t localhost/sessions-web web/
podman build -t localhost/sessions-web:latest web/ podman run -d --name sessions-web --restart unless-stopped \
--env-file ~/.config/sessions-web/env -p 127.0.0.1:8470:8470 \
# 1. Secrets (nothing is echoed; each command reads from a file or a hidden prompt) --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
podman secret create sessions-ssh-key ~/.ssh/<key> localhost/sessions-web
head -c 48 /dev/urandom | base64 -w0 | podman secret create sessions-web-secret -
read -rsp 'Web password (12+ chars): ' PW; echo
printf '%s\n' "$PW" | podman run --rm -i localhost/sessions-web:latest python3 /app/app.py hash-password --stdin \
| podman secret create sessions-password-hash - ; unset PW
# 2. Non-secret config + the dev box's pinned host key
install -d -m 700 ~/.config/sessions-web
install -m 600 web/env.example ~/.config/sessions-web/env
install -m 644 web/known_hosts.dev-box ~/.config/sessions-web/known_hosts
# 3. Check that the key works from this machine before involving the container
ssh -i ~/.ssh/<key> -p 14922 -o UserKnownHostsFile=web/known_hosts.dev-box agent@2.28.100.223 health
# 4. Run under systemd (starts at boot only with linger on for this user)
install -D -m 644 web/sessions-web.container ~/.config/containers/systemd/sessions-web.container
systemctl --user daemon-reload
systemctl --user start sessions-web
curl -s http://127.0.0.1:8470/healthz # → ok
``` ```
### Reverse proxy Then put it behind `forward_auth` in Caddy:
The container listens on `127.0.0.1:8470` only. Put it behind the proxy that already
terminates TLS on prod, for example at `sessions.reudy.net`. The proxy must set
`X-Forwarded-For` for the rate limiter (`SESSIONS_TRUST_PROXY=1`).
Caddy:
``` ```
sessions.reudy.net { sessions.reudy.net {
forward_auth 127.0.0.1:9091 {
uri /api/authz/forward-auth
copy_headers Remote-User Remote-Groups Remote-Email Remote-Name
}
reverse_proxy 127.0.0.1:8470 reverse_proxy 127.0.0.1:8470
} }
``` ```
nginx:
```
location / {
proxy_pass http://127.0.0.1:8470;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
```
### Updating prod
```sh
git pull && podman build -t localhost/sessions-web:latest web/ && systemctl --user restart sessions-web
```
## Troubleshooting ## Troubleshooting
| Symptom | Check | | Symptom | Check |
|---|---| |---|---|
| Page says "dev box unreachable: Permission denied" | Prod's outgoing IP isn't the one `reudy.net` resolves to. On the dev box, `sudo journalctl -u ssh -n 20` shows the source IP. `sessions-ctl refresh-access` shows what `from=` holds | | "forbidden: this page must be served behind Authelia" | The route has no forward_auth, or the user isn't in `SESSIONS_ALLOWED_USERS` |
| "Host key verification failed" | The dev box's host key changed. Update `known_hosts.dev-box` deliberately; never turn off checking | | Container exits with "configuration error" | One of the env values was pasted incompletely. Run `sessions-ctl keygen --rotate` again and paste all five lines |
| Page says "dev box unreachable: Permission denied" | Prod's outgoing IP isn't the one `reudy.net` resolves to, or the env holds an old key. On the dev box, `sudo journalctl -u ssh -n 20` shows the source IP. `sessions-ctl refresh-access` shows what `from=` holds |
| "Host key verification failed" | The dev box's host key changed. Check that the change is expected, then update `SESSIONS_DEV_HOST_KEY`. Never turn off checking |
| Session `failed` | `journalctl --user -u claude-session@NAME -n 50`. After 5 crashes in 10 min systemd gives up; fix the cause, then Start again | | Session `failed` | `journalctl --user -u claude-session@NAME -n 50`. After 5 crashes in 10 min systemd gives up; fix the cause, then Start again |
| "stuck on the folder-trust prompt" | `tmux -L claude-NAME attach`, accept, detach. Then the trust field has moved in a Claude Code update, so fix `trust_workspace()` | | "stuck on the folder-trust prompt" | `tmux -L claude-NAME attach`, accept, detach. Then the trust field has moved in a Claude Code update, so fix `trust_workspace()` |
| No "Open in Claude" link | The link is read from the pane once Remote Control is up; refresh after a few seconds | | No "Open in Claude" link | The link is read from the pane once Remote Control is up; refresh after a few seconds |

20
compose.yaml Normal file
View file

@ -0,0 +1,20 @@
# Deployed on prod by the panel (reudy-net/panel): it builds this, injects the
# app's environment variables, and publishes web:8470 on 127.0.0.1 for the
# route, which must have Authelia turned on. The variables come from running
# `sessions-ctl keygen` on the dev box — see README "Deploy on prod".
services:
web:
build: ./web
image: localhost/sessions-web:latest
restart: unless-stopped
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
healthcheck:
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8470/healthz', timeout=4)"]
interval: 60s
timeout: 5s

View file

@ -21,5 +21,10 @@ sessions = "ssh://git@git.reudy.net:14922/reudy-net/sessions.git"
# prod's key may only connect from the address(es) this name resolves to. # prod's key may only connect from the address(es) this name resolves to.
# Re-resolved hourly by sessions-access-refresh.timer. # Re-resolved hourly by sessions-access-refresh.timer.
allow_from_host = "reudy.net" allow_from_host = "reudy.net"
# The public half of the key the web app container uses. # The public half of the key the web app container uses. Written by
public_key = "ssh-ed25519 AAAA… comment" # `sessions-ctl keygen`; you don't need to edit it by hand.
# public_key = "ssh-ed25519 AAAA… sessions-web"
# Printed by keygen as SESSIONS_DEV_HOST / SESSIONS_DEV_PORT. By default it's
# the address this box uses to reach the internet, and 14922.
# advertise_host = "2.28.100.223"
# port = 14922

View file

@ -24,7 +24,7 @@ done
if [[ ! -e "$cfg_dir/config.toml" ]]; then if [[ ! -e "$cfg_dir/config.toml" ]]; then
install -m 600 "$here/config.example.toml" "$cfg_dir/config.toml" install -m 600 "$here/config.example.toml" "$cfg_dir/config.toml"
echo "created $cfg_dir/config.toml — edit [repos] and [ssh_access], then re-run." echo "created $cfg_dir/config.toml — edit [repos] and [ssh_access], then run: sessions-ctl keygen"
fi fi
chmod 600 "$cfg_dir/config.toml" chmod 600 "$cfg_dir/config.toml"
@ -41,6 +41,6 @@ fi
if grep -Eq '^public_key = "ssh-[a-z0-9-]+ AAAA[A-Za-z0-9+/=]{20,}' "$cfg_dir/config.toml"; then if grep -Eq '^public_key = "ssh-[a-z0-9-]+ AAAA[A-Za-z0-9+/=]{20,}' "$cfg_dir/config.toml"; then
"$bin/sessions-ctl" refresh-access "$bin/sessions-ctl" refresh-access
else else
echo "ssh_access.public_key not set yet — skipping authorized_keys." echo "no key for prod yet — run: sessions-ctl keygen"
fi fi
echo "installed. try: sessions-ctl health" echo "installed. try: sessions-ctl health"

View file

@ -18,13 +18,16 @@ Each session is:
systemd is the source of truth for "should this run": a session that is systemd is the source of truth for "should this run": a session that is
enabled starts at boot (the user has linger on) and is restarted if it dies. enabled starts at boot (the user has linger on) and is restarted if it dies.
Output is always one JSON object on stdout. Exit codes: 0 ok, 1 error, 2 usage. Output is one JSON object on stdout (except `keygen`, which prints an env
block to copy). Exit codes: 0 ok, 1 error, 2 usage.
Standard library only, so it runs with the system python3. Standard library only, so it runs with the system python3.
""" """
from __future__ import annotations from __future__ import annotations
import base64
import datetime as dt import datetime as dt
import getpass
import fcntl import fcntl
import json import json
import os import os
@ -47,6 +50,7 @@ CLAUDE_JSON = Path(os.environ.get("SESSIONS_CLAUDE_JSON", HOME / ".claude.json")
CLAUDE_PROJECTS = HOME / ".claude/projects" CLAUDE_PROJECTS = HOME / ".claude/projects"
AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys")) AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys"))
SELF_PATH = HOME / ".local/bin/sessions-ctl" SELF_PATH = HOME / ".local/bin/sessions-ctl"
HOST_KEY_PATH = os.environ.get("SESSIONS_HOST_KEY", "/etc/ssh/ssh_host_ed25519_key.pub")
UNIT = "claude-session@{}.service" UNIT = "claude-session@{}.service"
KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys
@ -74,7 +78,8 @@ class UserError(Exception):
# ---------------------------------------------------------------- config/state # ---------------------------------------------------------------- config/state
def load_config(path: Path = CONFIG_PATH) -> dict: def load_config(path: Path | None = None) -> dict:
path = path or CONFIG_PATH # looked up at call time, so tests can repoint it
cfg = dict(DEFAULTS) cfg = dict(DEFAULTS)
if path.exists(): if path.exists():
with path.open("rb") as f: with path.open("rb") as f:
@ -399,6 +404,80 @@ def cmd_refresh_access(cfg: dict, args: list[str]) -> dict:
return {"changed": changed, "from": ips} return {"changed": changed, "from": ips}
def cmd_keygen(cfg: dict, args: list[str]) -> dict:
"""Local only. Make the key prod uses and print its env block once.
The pair is generated in RAM (XDG_RUNTIME_DIR). The public half goes into
config.toml and authorized_keys; the private half is printed as one base64
line for the container's environment and then deleted, so it exists only
where you paste it.
"""
if [a for a in args if a != "--rotate"]:
raise UserError("usage: sessions-ctl keygen [--rotate]")
if cfg["ssh_access"].get("public_key", "").startswith("ssh-") and "--rotate" not in args:
raise UserError("a key is already configured; `keygen --rotate` replaces it "
"(prod stops working until its environment is updated)")
if not cfg["ssh_access"].get("allow_from_host"):
raise UserError("config: set ssh_access.allow_from_host first")
tmp = Path(tempfile.mkdtemp(dir=_user_env()["XDG_RUNTIME_DIR"], prefix="sessions-keygen-"))
try:
_run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "sessions-web", "-f", str(tmp / "id")])
public = (tmp / "id.pub").read_text().strip()
private_b64 = base64.b64encode((tmp / "id").read_bytes()).decode()
finally:
shutil.rmtree(tmp, ignore_errors=True)
text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else ""
atomic_write(CONFIG_PATH, set_toml_string(text, "ssh_access", "public_key", public), 0o600)
access = cmd_refresh_access(load_config(), [])
host_key = " ".join(Path(HOST_KEY_PATH).read_text().split()[:2])
env_block = "\n".join([
f"SESSIONS_DEV_HOST={cfg['ssh_access'].get('advertise_host') or public_address()}",
f"SESSIONS_DEV_PORT={cfg['ssh_access'].get('port', 14922)}",
f"SESSIONS_DEV_USER={getpass.getuser()}",
f"SESSIONS_DEV_HOST_KEY={host_key}",
f"SESSIONS_SSH_KEY_B64={private_b64}",
])
note = ("Paste these lines into the sessions app's environment on prod (panel -> app -> Environment).\n"
"The private key exists nowhere else now. Clear this screen afterwards (`clear`, and your\n"
"terminal's scrollback). The key only works from: " + ", ".join(access["from"]))
return {"text": env_block, "note": note, "from": access["from"]}
def set_toml_string(text: str, section: str, key: str, value: str) -> str:
"""Set `key = "value"` inside [section] of a simple TOML file, keeping the rest."""
if '"' in value or "\\" in value or "\n" in value:
raise UserError("refusing to write an unusual value into config.toml")
lines, out, in_section, done = text.splitlines(), [], False, False
for line in lines:
stripped = line.strip()
if stripped.startswith("["):
if in_section and not done:
out.append(f'{key} = "{value}"')
done = True
in_section = stripped == f"[{section}]"
elif in_section and re.match(rf"^{re.escape(key)}\s*=", stripped):
if not done:
out.append(f'{key} = "{value}"')
done = True
continue
out.append(line)
if not done:
if not in_section:
out += ["", f"[{section}]"]
out.append(f'{key} = "{value}"')
return "\n".join(out) + "\n"
def public_address() -> str:
"""The source address this box uses to reach the internet (no packet is sent)."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("192.0.2.1", 9)) # TEST-NET-1; UDP connect only picks a route
return s.getsockname()[0]
# ---------------------------------------------------------------- helpers # ---------------------------------------------------------------- helpers
@ -449,6 +528,7 @@ VERBS = {
"health": cmd_health, "health": cmd_health,
"delete": cmd_delete, "delete": cmd_delete,
"refresh-access": cmd_refresh_access, "refresh-access": cmd_refresh_access,
"keygen": cmd_keygen,
"_launch": cmd_launch, "_launch": cmd_launch,
} }
@ -484,6 +564,11 @@ def main(argv: list[str]) -> int:
if not argv or argv[0] not in VERBS: if not argv or argv[0] not in VERBS:
raise UserError(f"usage: sessions-ctl {{{'|'.join(v for v in VERBS if not v.startswith('_'))}}} …") raise UserError(f"usage: sessions-ctl {{{'|'.join(v for v in VERBS if not v.startswith('_'))}}} …")
result = VERBS[argv[0]](load_config(), argv[1:]) result = VERBS[argv[0]](load_config(), argv[1:])
if "text" in result and not remote:
print(result["text"]) # keygen: KEY=VALUE lines only, safe to paste as-is
if result.get("note"):
print(result["note"], file=sys.stderr)
else:
print(json.dumps({"ok": True, **result})) print(json.dumps({"ok": True, **result}))
return 0 return 0
except UserError as e: except UserError as e:

View file

@ -126,5 +126,73 @@ class MainContract(unittest.TestCase):
self.assertFalse(json.loads(buf.getvalue())["ok"]) self.assertFalse(json.loads(buf.getvalue())["ok"])
class TomlEdit(unittest.TestCase):
BASE = 'max_running = 2\n\n[repos]\na = "x"\n\n[ssh_access]\nallow_from_host = "reudy.net"\npublic_key = "old"\n'
def test_replaces_in_place(self):
out = sc.set_toml_string(self.BASE, "ssh_access", "public_key", "ssh-ed25519 AAAAnew c")
self.assertIn('public_key = "ssh-ed25519 AAAAnew c"', out)
self.assertNotIn('"old"', out)
self.assertEqual(out.count("public_key"), 1)
self.assertIn('a = "x"', out)
def test_adds_key_or_section(self):
no_key = self.BASE.replace('public_key = "old"\n', "")
self.assertIn('public_key = "k"', sc.set_toml_string(no_key, "ssh_access", "public_key", "k"))
out = sc.set_toml_string('max_running = 2\n', "ssh_access", "public_key", "k")
self.assertTrue(out.endswith('[ssh_access]\npublic_key = "k"\n'))
def test_same_key_in_other_section_untouched(self):
text = '[other]\npublic_key = "keep"\n[ssh_access]\npublic_key = "old"\n'
out = sc.set_toml_string(text, "ssh_access", "public_key", "new")
self.assertIn('public_key = "keep"', out)
self.assertIn('public_key = "new"', out)
def test_rejects_quotes(self):
with self.assertRaises(sc.UserError):
sc.set_toml_string("", "s", "k", 'a" \nx = "y')
class Keygen(unittest.TestCase):
def test_keygen_end_to_end_in_temp_dirs(self):
import base64, os
from unittest import mock
with tempfile.TemporaryDirectory() as d:
d = Path(d)
cfg = d / "config.toml"
cfg.write_text('[ssh_access]\nallow_from_host = "reudy.net"\npublic_key = "ssh-ed25519 AAAAold vps-manual"\n')
ak = d / "authorized_keys"
ak.write_text("ssh-ed25519 AAAAmine me@laptop\n" + 'from="1.1.1.1",restrict ssh-ed25519 AAAAold sessions-manager\n')
hk = d / "host.pub"
hk.write_text("ssh-ed25519 AAAAhostkey root@box\n")
with mock.patch.object(sc, "CONFIG_PATH", cfg), mock.patch.object(sc, "AUTHORIZED_KEYS", ak), \
mock.patch.object(sc, "HOST_KEY_PATH", str(hk)), mock.patch.object(sc, "resolve", lambda h: ["37.205.10.63"]), \
mock.patch.dict(os.environ, {"XDG_RUNTIME_DIR": str(d)}):
with self.assertRaises(sc.UserError): # existing key needs --rotate
sc.cmd_keygen(sc.load_config(cfg), [])
r = sc.cmd_keygen(sc.load_config(cfg), ["--rotate"])
env = dict(line.split("=", 1) for line in r["text"].splitlines())
self.assertEqual(set(env), {"SESSIONS_DEV_HOST", "SESSIONS_DEV_PORT", "SESSIONS_DEV_USER",
"SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64"})
self.assertEqual(env["SESSIONS_DEV_HOST_KEY"], "ssh-ed25519 AAAAhostkey")
priv = base64.b64decode(env["SESSIONS_SSH_KEY_B64"], validate=True)
self.assertTrue(priv.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"))
# public half landed in config and authorized_keys; old key gone; other keys kept
new_pub = sc.load_config(cfg)["ssh_access"]["public_key"]
self.assertTrue(new_pub.startswith("ssh-ed25519 ") and "AAAAold" not in new_pub)
keys = ak.read_text()
self.assertIn("me@laptop", keys)
self.assertNotIn("AAAAold", keys)
self.assertIn(new_pub.split()[1], keys)
self.assertIn('from="37.205.10.63"', keys)
# nothing private left behind in the runtime dir
self.assertEqual([p.name for p in d.iterdir() if p.name.startswith("sessions-keygen-")], [])
def test_keygen_is_local_only(self):
with self.assertRaises(sc.UserError):
sc.parse_remote("keygen --rotate")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View file

@ -1,5 +1,5 @@
# sessions-web: the prod half of the session manager. # sessions-web: the prod half of the session manager.
# Build: podman build -t localhost/sessions-web:latest web/ # Configured entirely by environment variables (see app.py); no mounts needed.
FROM docker.io/library/python:3.13-slim FROM docker.io/library/python:3.13-slim
RUN apt-get update \ RUN apt-get update \
@ -9,8 +9,6 @@ RUN apt-get update \
WORKDIR /app WORKDIR /app
COPY app.py /app/app.py COPY app.py /app/app.py
# Mount points must already exist: the container runs with a read-only root.
RUN touch /app/ssh_key /app/known_hosts
USER 10001 USER 10001
ENV PYTHONUNBUFFERED=1 SESSIONS_LISTEN=0.0.0.0:8470 ENV PYTHONUNBUFFERED=1 SESSIONS_LISTEN=0.0.0.0:8470

View file

@ -1,137 +1,91 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""sessions-web — a small password-protected page for starting Claude sessions. """sessions-web — a small page for starting Claude sessions on the dev box.
Runs on prod (in a container). It never touches Claude itself: every action is Runs on prod in a container, behind Authelia (Caddy forward_auth). It has no
one `ssh dev-box <verb> <args>` call to sessions-ctl, which the dev box pins to login of its own: it serves only requests that carry the user header Authelia
a forced command. Standard library only; no JavaScript on the page. sets, and it never touches Claude itself — every action is one
`ssh dev-box <verb> <args>` call to sessions-ctl, which the dev box pins to a
forced command. Standard library only; no JavaScript on the page.
Configuration (environment): Configuration (environment; every value is one line, so the panel can set it).
`sessions-ctl keygen` on the dev box prints the first five ready to paste:
SESSIONS_DEV_HOST dev box address (required) SESSIONS_DEV_HOST dev box address (required)
SESSIONS_DEV_PORT default 14922 SESSIONS_DEV_PORT default 14922
SESSIONS_DEV_USER default agent SESSIONS_DEV_USER default agent
SESSIONS_SSH_KEY private key file (default /app/ssh_key) SESSIONS_DEV_HOST_KEY dev box SSH host key, "ssh-ed25519 AAAA…" (required)
SESSIONS_KNOWN_HOSTS pinned host key file (default /app/known_hosts) SESSIONS_SSH_KEY_B64 base64 of the OpenSSH private key (required)
SESSIONS_PASSWORD_HASH output of `app.py hash-password` (required) SESSIONS_AUTH_HEADER header the proxy sets after login (default Remote-User)
SESSIONS_SECRET >= 32 random chars for signing cookies (required) SESSIONS_ALLOWED_USERS optional comma-separated usernames; empty = any
user Authelia lets through
SESSIONS_LISTEN default 0.0.0.0:8470 (inside the container) SESSIONS_LISTEN default 0.0.0.0:8470 (inside the container)
SESSIONS_COOKIE_SECURE 1 (default) = cookie only over HTTPS; 0 for local tests
SESSIONS_TRUST_PROXY 1 = take the client IP from X-Forwarded-For (only
when a reverse proxy you control sets it)
""" """
from __future__ import annotations from __future__ import annotations
import base64 import base64
import getpass import binascii
import hashlib
import hmac
import html import html
import json import json
import os import os
import secrets import re
import shlex import shlex
import signal import signal
import subprocess import subprocess
import sys import sys
import threading import tempfile
import time
import urllib.parse import urllib.parse
from http import HTTPStatus from http import HTTPStatus
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
COOKIE = "sessions_auth"
SESSION_TTL = 12 * 3600
NAME_CHARS = set("abcdefghijklmnopqrstuvwxyz0123456789-") NAME_CHARS = set("abcdefghijklmnopqrstuvwxyz0123456789-")
HOST_KEY_RE = re.compile(r"^(ssh-ed25519|ecdsa-sha2-nistp256|ssh-rsa) [A-Za-z0-9+/=]+$")
# ---------------------------------------------------------------- passwords # ---------------------------------------------------------------- config
def hash_password(password: str, *, n: int = 2**15, r: int = 8, p: int = 1) -> str: class ConfigError(Exception):
salt = secrets.token_bytes(16) pass
dk = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, maxmem=64 * 1024 * 1024)
return "scrypt${}${}${}${}${}".format(n, r, p, base64.b64encode(salt).decode(), base64.b64encode(dk).decode())
def verify_password(password: str, encoded: str) -> bool: def materialise_ssh_files(env: dict, directory: str) -> tuple[str, str]:
"""Write the private key and a known_hosts file from env into `directory`.
ssh wants files; the panel (and `podman run -e`) gives us single-line env
values. `directory` is a private (0700) temp dir on the container's /tmp.
"""
try: try:
algo, n, r, p, salt, dk = encoded.split("$") key = base64.b64decode(env.get("SESSIONS_SSH_KEY_B64", "").strip(), validate=True)
if algo != "scrypt": except (binascii.Error, ValueError):
return False raise ConfigError("SESSIONS_SSH_KEY_B64 is not valid base64")
got = hashlib.scrypt(password.encode(), salt=base64.b64decode(salt), n=int(n), r=int(r), p=int(p), maxmem=64 * 1024 * 1024) if not key.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"):
return hmac.compare_digest(got, base64.b64decode(dk)) raise ConfigError("SESSIONS_SSH_KEY_B64 does not decode to an OpenSSH private key")
except (ValueError, TypeError): host_key = env.get("SESSIONS_DEV_HOST_KEY", "").strip()
return False if not HOST_KEY_RE.fullmatch(host_key):
raise ConfigError('SESSIONS_DEV_HOST_KEY must look like "ssh-ed25519 AAAA…"')
key_path = os.path.join(directory, "id")
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as f:
f.write(key if key.endswith(b"\n") else key + b"\n")
# ---------------------------------------------------------------- cookies host, port = env["SESSIONS_DEV_HOST"], env.get("SESSIONS_DEV_PORT", "14922")
known = os.path.join(directory, "known_hosts")
with open(known, "w") as f:
def sign(secret: bytes, payload: dict) -> str: f.write(f"[{host}]:{port} {host_key}\n")
body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode() return key_path, known
mac = hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()
return f"{body}.{mac}"
def unsign(secret: bytes, token: str, now: float | None = None) -> dict | None:
try:
body, mac = token.rsplit(".", 1)
except ValueError:
return None
if not hmac.compare_digest(mac, hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()):
return None
try:
payload = json.loads(base64.urlsafe_b64decode(body))
except ValueError:
return None
if payload.get("exp", 0) < (now or time.time()):
return None
return payload
def csrf_token(secret: bytes, sid: str) -> str:
return hmac.new(secret, f"csrf:{sid}".encode(), hashlib.sha256).hexdigest()
# ---------------------------------------------------------------- rate limit
class RateLimiter:
"""Failed logins: at most `per_ip` per window per client, `total` overall."""
def __init__(self, per_ip: int = 5, total: int = 20, window: int = 900):
self.per_ip, self.total, self.window = per_ip, total, window
self.fails: dict[str, list[float]] = {}
self.lock = threading.Lock()
def _prune(self, now: float) -> None:
for ip in list(self.fails):
self.fails[ip] = [t for t in self.fails[ip] if now - t < self.window]
if not self.fails[ip]:
del self.fails[ip]
def blocked(self, ip: str, now: float | None = None) -> bool:
now = now or time.time()
with self.lock:
self._prune(now)
return len(self.fails.get(ip, [])) >= self.per_ip or sum(map(len, self.fails.values())) >= self.total
def fail(self, ip: str, now: float | None = None) -> None:
with self.lock:
self.fails.setdefault(ip, []).append(now or time.time())
# ---------------------------------------------------------------- dev box link # ---------------------------------------------------------------- dev box link
class DevBox: class DevBox:
def __init__(self, env: dict): def __init__(self, env: dict, key_path: str, known_hosts: str):
self.host = env["SESSIONS_DEV_HOST"] self.host = env["SESSIONS_DEV_HOST"]
self.port = env.get("SESSIONS_DEV_PORT", "14922") self.port = env.get("SESSIONS_DEV_PORT", "14922")
self.user = env.get("SESSIONS_DEV_USER", "agent") self.user = env.get("SESSIONS_DEV_USER", "agent")
self.key = env.get("SESSIONS_SSH_KEY", "/app/ssh_key") self.key = key_path
self.known_hosts = env.get("SESSIONS_KNOWN_HOSTS", "/app/known_hosts") self.known_hosts = known_hosts
def argv(self, *args: str) -> list[str]: def argv(self, *args: str) -> list[str]:
for a in args: # belt and braces: the dev box validates too for a in args: # belt and braces: the dev box validates too
@ -170,6 +124,28 @@ class DevBox:
return {"ok": False, "error": f"dev box unreachable: {err[:200]}"} return {"ok": False, "error": f"dev box unreachable: {err[:200]}"}
# ---------------------------------------------------------------- request checks
def same_origin(headers, host: str) -> bool:
"""Reject cross-site POSTs without needing a CSRF secret.
Browsers send Sec-Fetch-Site and/or Origin on every POST. Either must say
the request came from this site; a request with neither is refused.
"""
site = headers.get("Sec-Fetch-Site")
if site is not None:
return site == "same-origin"
origin = headers.get("Origin")
if origin:
return urllib.parse.urlsplit(origin).netloc == host
return False
def allowed_user(user: str, allowed: set[str]) -> bool:
return bool(user) and (not allowed or user in allowed)
# ---------------------------------------------------------------- HTML # ---------------------------------------------------------------- HTML
CSS = """ CSS = """
@ -205,18 +181,8 @@ def e(v) -> str:
return html.escape(str(v if v is not None else "")) return html.escape(str(v if v is not None else ""))
def login_page(error: str = "") -> bytes: def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
flash = f'<div class="flash err">{e(error)}</div>' if error else "" parts = [f'<header><h1>Sessions</h1><span class="meta">{e(user)}</span></header>']
return page("Sessions · sign in", f"""
<header><h1>Sessions</h1></header>{flash}
<form method="post" action="/login" class="card">
<label for="pw">Password</label><input id="pw" name="password" type="password" autocomplete="current-password" autofocus required>
<div class="actions"><button class="primary">Sign in</button></div></form>""")
def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | None) -> bytes:
parts = ['<header><h1>Sessions</h1><form method="post" action="/logout" class="inline">'
f'<input type="hidden" name="csrf" value="{e(csrf)}"><button>Sign out</button></form></header>']
if flash: if flash:
parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>') parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>')
if not listing.get("ok"): if not listing.get("ok"):
@ -236,12 +202,11 @@ def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | No
<span class="pill {e(s["state"])}">{e(s["state"])}</span></div> <span class="pill {e(s["state"])}">{e(s["state"])}</span></div>
<div class="meta">{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}</div>{warn} <div class="meta">{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}</div>{warn}
<div class="actions">{link}<form method="post" action="/{verb}" class="inline"> <div class="actions">{link}<form method="post" action="/{verb}" class="inline">
<input type="hidden" name="csrf" value="{e(csrf)}"><input type="hidden" name="name" value="{e(s["name"])}"> <input type="hidden" name="name" value="{e(s["name"])}">
<button>{verb.title()}</button></form></div></div>""") <button>{verb.title()}</button></form></div></div>""")
options = "".join(f'<option value="{e(r)}">{e(r)}</option>' for r in repos.get("repos", [])) options = "".join(f'<option value="{e(r)}">{e(r)}</option>' for r in repos.get("repos", []))
parts.append(f"""<h2>New session</h2><form method="post" action="/create" class="card"> parts.append(f"""<h2>New session</h2><form method="post" action="/create" class="card">
<input type="hidden" name="csrf" value="{e(csrf)}">
<label for="name">Name</label><input id="name" name="name" required pattern="[a-z0-9][a-z0-9\\-]{{0,31}}" placeholder="fix-login" autocapitalize="none" autocomplete="off"> <label for="name">Name</label><input id="name" name="name" required pattern="[a-z0-9][a-z0-9\\-]{{0,31}}" placeholder="fix-login" autocapitalize="none" autocomplete="off">
<label for="repo">Repository</label><select id="repo" name="repo" required>{options}</select> <label for="repo">Repository</label><select id="repo" name="repo" required>{options}</select>
<label for="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off"> <label for="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off">
@ -254,15 +219,10 @@ def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | No
class App: class App:
def __init__(self, env: dict): def __init__(self, env: dict, dev: DevBox):
self.password_hash = env["SESSIONS_PASSWORD_HASH"].strip() self.dev = dev
self.secret = env["SESSIONS_SECRET"].strip().encode() self.auth_header = env.get("SESSIONS_AUTH_HEADER", "Remote-User")
if len(self.secret) < 32: self.allowed_users = {u.strip() for u in env.get("SESSIONS_ALLOWED_USERS", "").split(",") if u.strip()}
raise SystemExit("SESSIONS_SECRET must be at least 32 characters")
self.cookie_secure = env.get("SESSIONS_COOKIE_SECURE", "1") == "1"
self.trust_proxy = env.get("SESSIONS_TRUST_PROXY", "0") == "1"
self.dev = DevBox(env)
self.limiter = RateLimiter()
def make_handler(app: App): def make_handler(app: App):
@ -270,14 +230,11 @@ def make_handler(app: App):
server_version = "sessions-web" server_version = "sessions-web"
sys_version = "" sys_version = ""
# -- plumbing def user(self) -> str:
def client_ip(self) -> str: return (self.headers.get(app.auth_header) or "").strip()
if app.trust_proxy and self.headers.get("X-Forwarded-For"):
return self.headers["X-Forwarded-For"].split(",")[-1].strip()
return self.client_address[0]
def log_message(self, fmt, *args): def log_message(self, fmt, *args):
sys.stderr.write(f"{self.client_ip()} {fmt % args}\n") sys.stderr.write(f"{self.user() or '-'} {fmt % args}\n")
def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", headers: dict | None = None): def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", headers: dict | None = None):
self.send_response(status) self.send_response(status)
@ -293,19 +250,17 @@ def make_handler(app: App):
if self.command != "HEAD": if self.command != "HEAD":
self.wfile.write(body) self.wfile.write(body)
def redirect(self, to: str, cookie: str | None = None): def refuse_unauthenticated(self) -> bool:
headers = {"Location": to} """Fail closed if the request didn't come through Authelia.
if cookie is not None:
headers["Set-Cookie"] = cookie
self.send(HTTPStatus.SEE_OTHER, headers=headers)
def cookie_header(self, value: str, max_age: int) -> str: Behind Caddy's forward_auth the header is always set by Authelia
secure = "; Secure" if app.cookie_secure else "" (copy_headers overwrites whatever the client sent). If it's
return f"{COOKIE}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Strict{secure}" missing, the route has lost its forward_auth — don't serve.
"""
def auth(self) -> dict | None: if allowed_user(self.user(), app.allowed_users):
jar = SimpleCookie(self.headers.get("Cookie", "")) return False
return unsign(app.secret, jar[COOKIE].value) if COOKIE in jar else None self.send(403, b"forbidden: this page must be served behind Authelia\n", "text/plain")
return True
def form(self) -> dict: def form(self) -> dict:
n = int(self.headers.get("Content-Length") or 0) n = int(self.headers.get("Content-Length") or 0)
@ -313,7 +268,6 @@ def make_handler(app: App):
return {} return {}
return {k: v[0] for k, v in urllib.parse.parse_qs(self.rfile.read(n).decode(errors="replace")).items()} return {k: v[0] for k, v in urllib.parse.parse_qs(self.rfile.read(n).decode(errors="replace")).items()}
# -- routes
def do_HEAD(self): def do_HEAD(self):
self.do_GET() self.do_GET()
@ -321,15 +275,12 @@ def make_handler(app: App):
path = urllib.parse.urlsplit(self.path).path path = urllib.parse.urlsplit(self.path).path
if path == "/healthz": if path == "/healthz":
return self.send(200, b"ok\n", "text/plain") return self.send(200, b"ok\n", "text/plain")
if self.refuse_unauthenticated():
return
if path == "/app.css": if path == "/app.css":
return self.send(200, CSS.encode(), "text/css") return self.send(200, CSS.encode(), "text/css")
if path == "/login":
return self.send(200, login_page())
if path != "/": if path != "/":
return self.send(404, b"not found\n", "text/plain") return self.send(404, b"not found\n", "text/plain")
sess = self.auth()
if not sess:
return self.redirect("/login")
flash = None flash = None
q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)
if "ok" in q: if "ok" in q:
@ -338,27 +289,15 @@ def make_handler(app: App):
flash = ("err", q["err"][0][:300]) flash = ("err", q["err"][0][:300])
listing = app.dev.call("list") listing = app.dev.call("list")
repos = app.dev.call("repos") if listing.get("ok") else {} repos = app.dev.call("repos") if listing.get("ok") else {}
self.send(200, dashboard(listing, repos, csrf_token(app.secret, sess["sid"]), flash)) self.send(200, dashboard(listing, repos, self.user(), flash))
def do_POST(self): def do_POST(self):
if self.refuse_unauthenticated():
return
if not same_origin(self.headers, self.headers.get("Host", "")):
return self.send(403, b"forbidden: cross-site request\n", "text/plain")
path = urllib.parse.urlsplit(self.path).path path = urllib.parse.urlsplit(self.path).path
f = self.form() f = self.form()
if path == "/login":
ip = self.client_ip()
if app.limiter.blocked(ip):
return self.send(429, login_page("Too many attempts. Try again in 15 minutes."))
if not verify_password(f.get("password", ""), app.password_hash):
app.limiter.fail(ip)
self.log_message("login failed")
return self.send(401, login_page("Wrong password."))
token = sign(app.secret, {"sid": secrets.token_urlsafe(16), "exp": int(time.time()) + SESSION_TTL})
return self.redirect("/", self.cookie_header(token, SESSION_TTL))
sess = self.auth()
if not sess or not hmac.compare_digest(f.get("csrf", ""), csrf_token(app.secret, sess["sid"])):
return self.send(403, b"forbidden\n", "text/plain")
if path == "/logout":
return self.redirect("/login", self.cookie_header("", 0))
if path == "/create": if path == "/create":
args = [f.get("name", "").strip(), f.get("repo", "")] args = [f.get("name", "").strip(), f.get("repo", "")]
if f.get("base", "").strip(): if f.get("base", "").strip():
@ -370,40 +309,34 @@ def make_handler(app: App):
done = {"/start": "started", "/stop": "stopped"}[path] + f" {f.get('name', '')}" done = {"/start": "started", "/stop": "stopped"}[path] + f" {f.get('name', '')}"
else: else:
return self.send(404, b"not found\n", "text/plain") return self.send(404, b"not found\n", "text/plain")
self.log_message("%s %s -> %s", path, f.get("name", ""), "ok" if r.get("ok") else r.get("error"))
key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed")) key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed"))
self.redirect("/?" + urllib.parse.urlencode({key: msg})) self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + urllib.parse.urlencode({key: msg})})
return Handler return Handler
def main(argv: list[str]) -> int: def main(argv: list[str]) -> int:
if argv[:1] == ["hash-password"]:
# --stdin: read the password from a pipe (see README) so that no prompt
# text can end up in the output that is piped into `podman secret create`.
if argv[1:] == ["--stdin"]:
pw = sys.stdin.readline().rstrip("\n")
else:
pw = getpass.getpass("New password: ")
if getpass.getpass("Again: ") != pw:
print("passwords differ", file=sys.stderr)
return 1
if len(pw) < 12:
print("use at least 12 characters", file=sys.stderr)
return 1
sys.stdout.write(hash_password(pw))
return 0
env = dict(os.environ) env = dict(os.environ)
missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_PASSWORD_HASH", "SESSIONS_SECRET") if not env.get(k)] missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64") if not env.get(k)]
if missing: if missing:
print(f"missing configuration: {', '.join(missing)}", file=sys.stderr) print(f"missing configuration: {', '.join(missing)} (run `sessions-ctl keygen` on the dev box)", file=sys.stderr)
return 1 return 1
app = App(env) workdir = tempfile.mkdtemp(prefix="sessions-web-") # 0700, on the container's /tmp tmpfs
try:
key_path, known = materialise_ssh_files(env, workdir)
except ConfigError as err:
print(f"configuration error: {err}", file=sys.stderr)
return 1
app = App(env, DevBox(env, key_path, known))
host, _, port = env.get("SESSIONS_LISTEN", "0.0.0.0:8470").rpartition(":") host, _, port = env.get("SESSIONS_LISTEN", "0.0.0.0:8470").rpartition(":")
server = ThreadingHTTPServer((host, int(port)), make_handler(app)) server = ThreadingHTTPServer((host, int(port)), make_handler(app))
# As PID 1 in a container Python gets no default SIGTERM handling, so # As PID 1 in a container Python gets no default SIGTERM handling, so
# `podman stop` would hang for 10 s and then SIGKILL. Exit cleanly instead. # `podman stop` would hang for 10 s and then SIGKILL. Exit cleanly instead.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
print(f"sessions-web listening on {host}:{port}, dev box {app.dev.user}@{app.dev.host}:{app.dev.port}", file=sys.stderr) who = ", ".join(sorted(app.allowed_users)) or "any user Authelia admits"
print(f"sessions-web on {host}:{port} → {app.dev.user}@{app.dev.host}:{app.dev.port}; "
f"auth header {app.auth_header}; allowed: {who}", file=sys.stderr)
server.serve_forever() server.serve_forever()
return 0 return 0

View file

@ -1,8 +0,0 @@
# ~/.config/sessions-web/env on prod — non-secret settings only (chmod 600 anyway).
# Secrets (SSH key, cookie secret, password hash) are podman secrets; see README.
SESSIONS_DEV_HOST=2.28.100.223
SESSIONS_DEV_PORT=14922
SESSIONS_DEV_USER=agent
# The reverse proxy in front sets X-Forwarded-For; trust it for rate limiting.
SESSIONS_TRUST_PROXY=1
SESSIONS_COOKIE_SECURE=1

View file

@ -1 +0,0 @@
[2.28.100.223]:14922 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEdLIHPjrkeUPfw1CDcIHC2Yydl39X46GBjmn6vqd+6E

View file

@ -1,34 +0,0 @@
# Podman Quadlet unit for prod. Install as the (rootless) user that runs it:
# ~/.config/containers/systemd/sessions-web.container
# then: systemctl --user daemon-reload && systemctl --user start sessions-web
# Starts at boot only if that user has linger (sudo loginctl enable-linger <user>).
[Unit]
Description=sessions-web (Claude session manager UI)
After=network-online.target
Wants=network-online.target
[Container]
Image=localhost/sessions-web:latest
ContainerName=sessions-web
# Loopback only — the reverse proxy on this host is the only way in.
PublishPort=127.0.0.1:8470:8470
EnvironmentFile=%h/.config/sessions-web/env
# Secrets live in podman's secret store, not in files next to this unit.
Secret=sessions-ssh-key,type=mount,target=/app/ssh_key,mode=0400,uid=10001
Secret=sessions-web-secret,type=env,target=SESSIONS_SECRET
Secret=sessions-password-hash,type=env,target=SESSIONS_PASSWORD_HASH
Volume=%h/.config/sessions-web/known_hosts:/app/known_hosts:ro,Z
ReadOnly=true
Tmpfs=/tmp
Tmpfs=/home/app
HealthCmd=python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8470/healthz', timeout=4)"
HealthInterval=60s
DropCapability=ALL
NoNewPrivileges=true
[Service]
Restart=always
RestartSec=5
[Install]
WantedBy=default.target

View file

@ -1,6 +1,10 @@
"""Unit tests for sessions-web. Run: python3 -m unittest discover -s web/tests""" """Unit tests for sessions-web. Run: python3 -m unittest discover -s web/tests"""
import base64
import importlib.util import importlib.util
import os
import stat
import tempfile
import unittest import unittest
from pathlib import Path from pathlib import Path
@ -8,64 +12,60 @@ _spec = importlib.util.spec_from_file_location("app", Path(__file__).parents[1]
app = importlib.util.module_from_spec(_spec) app = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(app) _spec.loader.exec_module(app)
SECRET = b"x" * 32 FAKE_KEY = b"-----BEGIN OPENSSH PRIVATE KEY-----\nAAAAfake\n-----END OPENSSH PRIVATE KEY-----\n"
ENV = {
"SESSIONS_DEV_HOST": "2.28.100.223",
"SESSIONS_DEV_HOST_KEY": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEdLIHPjrkeUPfw1CDcIHC2Yydl39X46GBjmn6vqd+6E",
"SESSIONS_SSH_KEY_B64": base64.b64encode(FAKE_KEY).decode(),
}
class Passwords(unittest.TestCase): class SshFiles(unittest.TestCase):
def test_roundtrip(self): def test_writes_private_key_and_pinned_host(self):
h = app.hash_password("correct horse battery", n=2**10) with tempfile.TemporaryDirectory() as d:
self.assertTrue(app.verify_password("correct horse battery", h)) key, known = app.materialise_ssh_files(ENV, d)
self.assertFalse(app.verify_password("wrong", h)) self.assertEqual(Path(key).read_bytes(), FAKE_KEY)
self.assertEqual(stat.S_IMODE(os.stat(key).st_mode), 0o600)
self.assertEqual(Path(known).read_text(), f"[2.28.100.223]:14922 {ENV['SESSIONS_DEV_HOST_KEY']}\n")
def test_garbage_hash_is_false_not_crash(self): def test_rejects_bad_values(self):
for h in ("", "plain", "scrypt$x$y$z$a$b", "md5$1$2$3$4$5"): bad = [
self.assertFalse(app.verify_password("pw", h)) {"SESSIONS_SSH_KEY_B64": "not base64!"},
{"SESSIONS_SSH_KEY_B64": base64.b64encode(b"hello").decode()},
{"SESSIONS_DEV_HOST_KEY": "ssh-ed25519"},
{"SESSIONS_DEV_HOST_KEY": "ssh-ed25519 AAAA\n[evil]:22 ssh-ed25519 AAAA"},
]
for override in bad:
with tempfile.TemporaryDirectory() as d, self.assertRaises(app.ConfigError, msg=override):
app.materialise_ssh_files({**ENV, **override}, d)
class Cookies(unittest.TestCase): class RequestChecks(unittest.TestCase):
def test_sign_unsign(self): def test_same_origin(self):
tok = app.sign(SECRET, {"sid": "abc", "exp": 2_000_000_000}) host = "sessions.reudy.net"
self.assertEqual(app.unsign(SECRET, tok)["sid"], "abc") self.assertTrue(app.same_origin({"Sec-Fetch-Site": "same-origin"}, host))
self.assertFalse(app.same_origin({"Sec-Fetch-Site": "cross-site", "Origin": f"https://{host}"}, host))
self.assertFalse(app.same_origin({"Sec-Fetch-Site": "same-site"}, host))
self.assertTrue(app.same_origin({"Origin": f"https://{host}"}, host))
self.assertFalse(app.same_origin({"Origin": "https://evil.example"}, host))
self.assertFalse(app.same_origin({}, host))
def test_tampered_or_expired(self): def test_allowed_user(self):
tok = app.sign(SECRET, {"sid": "abc", "exp": 2_000_000_000}) self.assertFalse(app.allowed_user("", set()))
body, mac = tok.rsplit(".", 1) self.assertTrue(app.allowed_user("reudy", set()))
forged = app.sign(b"y" * 32, {"sid": "abc", "exp": 2_000_000_000}) self.assertTrue(app.allowed_user("reudy", {"reudy"}))
self.assertIsNone(app.unsign(SECRET, forged)) self.assertFalse(app.allowed_user("mallory", {"reudy"}))
self.assertIsNone(app.unsign(SECRET, body + "." + "0" * 64))
self.assertIsNone(app.unsign(SECRET, "nodot"))
old = app.sign(SECRET, {"sid": "abc", "exp": 100})
self.assertIsNone(app.unsign(SECRET, old))
def test_csrf_bound_to_session(self):
self.assertNotEqual(app.csrf_token(SECRET, "a"), app.csrf_token(SECRET, "b"))
class Limiter(unittest.TestCase):
def test_per_ip_and_window(self):
rl = app.RateLimiter(per_ip=2, total=10, window=100)
rl.fail("1.1.1.1", now=0)
self.assertFalse(rl.blocked("1.1.1.1", now=1))
rl.fail("1.1.1.1", now=1)
self.assertTrue(rl.blocked("1.1.1.1", now=2))
self.assertFalse(rl.blocked("2.2.2.2", now=2))
self.assertFalse(rl.blocked("1.1.1.1", now=200))
def test_global_cap(self):
rl = app.RateLimiter(per_ip=5, total=3, window=100)
for i in range(3):
rl.fail(f"10.0.0.{i}", now=0)
self.assertTrue(rl.blocked("9.9.9.9", now=1))
class SshArgv(unittest.TestCase): class SshArgv(unittest.TestCase):
def setUp(self): def setUp(self):
self.dev = app.DevBox({"SESSIONS_DEV_HOST": "dev.example"}) self.dev = app.DevBox({"SESSIONS_DEV_HOST": "dev.example"}, "/k", "/kh")
def test_shape(self): def test_shape(self):
argv = self.dev.argv("create", "fix-login", "papure", "feature/x") argv = self.dev.argv("create", "fix-login", "papure", "feature/x")
self.assertEqual(argv[0], "ssh") self.assertEqual(argv[0], "ssh")
self.assertIn("StrictHostKeyChecking=yes", argv) self.assertIn("StrictHostKeyChecking=yes", argv)
self.assertIn("UserKnownHostsFile=/kh", argv)
self.assertEqual(argv[-2:], ["--", "create fix-login papure feature/x"]) self.assertEqual(argv[-2:], ["--", "create fix-login papure feature/x"])
def test_rejects_odd_arguments(self): def test_rejects_odd_arguments(self):
@ -81,8 +81,9 @@ class Rendering(unittest.TestCase):
"name": "<script>", "repo": "r", "branch": "b", "created_at": "2026-09-30T11:00:00", "name": "<script>", "repo": "r", "branch": "b", "created_at": "2026-09-30T11:00:00",
"state": "active", "enabled": True, "restarts": 0, "state": "active", "enabled": True, "restarts": 0,
"remote_control_url": 'https://claude.ai/code/session_x" onclick="x', "needs_attention": None}]} "remote_control_url": 'https://claude.ai/code/session_x" onclick="x', "needs_attention": None}]}
out = app.dashboard(listing, {"repos": ["papure"]}, "tok", ("err", "<b>")).decode() out = app.dashboard(listing, {"repos": ["papure"]}, "<u>", ("err", "<b>")).decode()
self.assertNotIn("<script>", out) self.assertNotIn("<script>", out)
self.assertNotIn("<u>", out)
self.assertNotIn('" onclick="', out) self.assertNotIn('" onclick="', out)
self.assertIn("&lt;b&gt;", out) self.assertIn("&lt;b&gt;", out)