#!/usr/bin/env python3 """sessions-web — a small page for starting Claude sessions on the dev box. Runs on prod in a container, behind Authelia (Caddy forward_auth). It has no login of its own: it serves only requests that carry the user header Authelia sets, and it never touches Claude itself — every action is one `ssh dev-box ` call to sessions-ctl, which the dev box pins to a forced command. Standard library only; no JavaScript on the page. 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_PORT default 14922 SESSIONS_DEV_USER default agent SESSIONS_DEV_HOST_KEY dev box SSH host key, "ssh-ed25519 AAAA…" (required) SESSIONS_SSH_KEY_B64 base64 of the OpenSSH private key (required) SESSIONS_AUTH_HEADER header the proxy sets after login (default Remote-User) SESSIONS_ALLOWED_USERS optional comma-separated usernames; empty = any user Authelia lets through SESSIONS_LISTEN default 0.0.0.0:8470 (inside the container) """ from __future__ import annotations import base64 import binascii import hashlib import html import json import os import re import shlex import signal import subprocess import sys import tempfile import threading import time import urllib.parse from concurrent.futures import ThreadPoolExecutor from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer # Characters an argument to the dev box may contain. shlex.join quotes each # argument and sessions-ctl splits it back without a shell, so a space is just # text; the dev box validates every argument again with its own patterns. ARG_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/ ") HOST_KEY_RE = re.compile(r"^(ssh-ed25519|ecdsa-sha2-nistp256|ssh-rsa) [A-Za-z0-9+/=]+$") # ---------------------------------------------------------------- config class ConfigError(Exception): pass 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: key = base64.b64decode(env.get("SESSIONS_SSH_KEY_B64", "").strip(), validate=True) except (binascii.Error, ValueError): raise ConfigError("SESSIONS_SSH_KEY_B64 is not valid base64") if not key.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"): raise ConfigError("SESSIONS_SSH_KEY_B64 does not decode to an OpenSSH private key") host_key = env.get("SESSIONS_DEV_HOST_KEY", "").strip() 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") 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: f.write(f"[{host}]:{port} {host_key}\n") return key_path, known # ---------------------------------------------------------------- dev box link class DevBox: """One `ssh` per call, sharing a single TCP connection. The dev box firewall rate-limits SSH (UFW `limit`: the 6th new connection from one address within 30 s is refused). A page view plus a couple of button presses easily makes that many calls, so calls are multiplexed over one master connection that stays up for CONTROL_PERSIST seconds after the last use. The control socket lives in the same private temp dir as the key. """ CONTROL_PERSIST = 120 def __init__(self, env: dict, key_path: str, known_hosts: str): self.host = env["SESSIONS_DEV_HOST"] self.port = env.get("SESSIONS_DEV_PORT", "14922") self.user = env.get("SESSIONS_DEV_USER", "agent") self.key = key_path self.known_hosts = known_hosts self.control_path = os.path.join(os.path.dirname(key_path), "cm-%C") def argv(self, *args: str) -> list[str]: for a in args: # belt and braces: the dev box validates too if not a or any(c not in ARG_CHARS for c in a) or a.startswith(("-", " ")): raise ValueError(f"refusing argument {a!r}") return [ "ssh", "-F", "/dev/null", "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "StrictHostKeyChecking=yes", "-o", f"UserKnownHostsFile={self.known_hosts}", "-o", "GlobalKnownHostsFile=/dev/null", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=3", "-o", "ControlMaster=auto", "-o", f"ControlPath={self.control_path}", "-o", f"ControlPersist={self.CONTROL_PERSIST}", "-i", self.key, "-p", str(self.port), "-l", self.user, self.host, "--", shlex.join(args), ] def call(self, *args: str, timeout: int = 60) -> dict: try: argv = self.argv(*args) except ValueError as e: return {"ok": False, "error": str(e)} try: r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: return {"ok": False, "error": "dev box did not answer in time"} try: return json.loads(r.stdout) except ValueError: err = (r.stderr.strip().splitlines() or ["no output"])[-1] 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) # ---------------------------------------------------------------- repo input # What the "Add repository" box accepts: OWNER/NAME, or a clone URL of the # git host the dev box adds from (ssh://, https:// or scp-style git@host:). REPO_INPUT_RE = re.compile( r"(?:(?Pssh|https?)://(?:[A-Za-z0-9._-]+@)?(?P[A-Za-z0-9.-]+)(?::\d+)?/" r"|git@(?P[A-Za-z0-9.-]+):)?" r"(?P[A-Za-z0-9][A-Za-z0-9._-]{0,39})/(?P[A-Za-z0-9][A-Za-z0-9._-]{0,99}?)(?:\.git)?/?" ) def parse_repo_input(text: str, base_url: str) -> tuple[str, str]: """'ssh://git@host:14922/team/App.git' -> ('team', 'App'). Raises ValueError. A URL must point at the same host as the dev box's base_url, because the dev box only ever builds URLs on that host: pasting a GitHub URL must fail loudly rather than silently add the same path from the git host. """ m = REPO_INPUT_RE.fullmatch(text.strip()) if not m or ".." in m["repo"]: raise ValueError("enter OWNER/NAME or the repo's clone URL") host = m["host"] or m["scp_host"] if host and host.lower() != (urllib.parse.urlsplit(base_url).hostname or "").lower(): raise ValueError(f"only repos on {urllib.parse.urlsplit(base_url).hostname} can be added") return m["owner"], m["repo"] def key_from_repo(repo: str) -> str: """'My_App.v2' -> 'my-app-v2': the allowlist key the page offers by default.""" return re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")[:32].rstrip("-") # ---------------------------------------------------------------- HTML STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") def _static(name: str) -> bytes: with open(os.path.join(STATIC, name), "rb") as f: return f.read() ASSETS = {"/app.css": (_static("app.css"), "text/css; charset=utf-8"), "/app.js": (_static("app.js"), "text/javascript; charset=utf-8")} # Asset URLs carry a content hash, so they can be cached forever and a deploy # still takes effect on the next page load. ASSET_VERSION = hashlib.sha256(b"".join(b for b, _ in ASSETS.values())).hexdigest()[:10] STATE_LABEL = {"active": "Running", "activating": "Starting", "deactivating": "Stopping", "reloading": "Reloading", "inactive": "Stopped", "failed": "Failed"} MARK = ('') def page(title: str, body: str) -> bytes: return f""" {html.escape(title)} {body}""".encode() def e(v) -> str: return html.escape(str(v if v is not None else "")) def action(verb: str, name: str, cls: str = "") -> str: return (f'
' f'' f'
') def badge(state: str) -> str: return f'{e(STATE_LABEL.get(state, state.title()))}' def session_card(s: dict, actions: str, cls: str = "") -> str: warn = f'
{e(s["needs_attention"])}
' if s.get("needs_attention") else "" restarts = f' · restarted {e(s["restarts"])}×' if s.get("restarts") else "" linked = " data-linked" if s.get("remote_control_url") else "" created = e(s["created_at"]) return f"""

{e(s.get("title") or s["name"])}

{badge(s["state"])}
{e(s["repo"])}/{e(s["branch"])}
Created {restarts}
{warn}
{actions}
""" def live_section(listing: dict) -> str: """The part of the page that changes on its own; app.js re-fetches and swaps it.""" parts = [] if not listing.get("ok"): parts.append(f'
{e(listing.get("error", "dev box error"))}
') sessions = [s for s in listing.get("sessions", []) if not s.get("archived")] archived = [s for s in listing.get("sessions", []) if s.get("archived")] running = sum(1 for s in sessions if s["state"] == "active") parts.append(f'

Active

' f'{running} of {e(listing.get("max_running", "?"))} running
') cards = [] for s in sessions: link = (f'Open in Claude' if s.get("remote_control_url") and s["state"] == "active" else "") verb = "stop" if s["enabled"] else "start" cards.append(session_card(s, link + action(verb, s["name"], "secondary") + action("archive", s["name"], "ghost"))) if not sessions and listing.get("ok"): cards.append('
No sessions yet' 'Create one and it shows up here and in the Claude app.
') parts.append(f'
{"".join(cards)}
') if archived: old = "".join(session_card(s, action("unarchive", s["name"], "secondary"), "archived") for s in archived) parts.append(f'
Archived {len(archived)}' f'
{old}
') return f'
{"".join(parts)}
' def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes: toast = f'
{e(flash[1])}
' if flash else "" options = "".join(f'' for r in repos.get("repos", [])) add = repos.get("add") add_form = "" if add: host = urllib.parse.urlsplit(add["base_url"]).hostname or "" owners = ", ".join(e(o) for o in add["owners"]) add_form = f"""

Add repository

Repos on {e(host)} owned by {owners}. The bot account must already have access. Sessions run with no permission prompts, so add only repos you trust.

""" body = f"""
{MARK}Sessions{e(user)}
{toast}

Sessions

Claude Code on the dev box, with Remote Control.

{live_section(listing)}
""" return page("Sessions", body) # ---------------------------------------------------------------- server # Buttons that take just a session name, and what the page says afterwards. DONE = {"/start": "Started", "/stop": "Stopped", "/archive": "Archived", "/unarchive": "Restored"} class App: REPOS_TTL = 300 # the allowlist rarely changes; add-repo refreshes it at once def __init__(self, env: dict, dev: DevBox): self.dev = dev self.auth_header = env.get("SESSIONS_AUTH_HEADER", "Remote-User") self.allowed_users = {u.strip() for u in env.get("SESSIONS_ALLOWED_USERS", "").split(",") if u.strip()} self._repos: dict | None = None self._repos_at = 0.0 self._lock = threading.Lock() def repos(self) -> dict: """The `repos` answer, cached so a page view costs one SSH call, not two.""" with self._lock: if self._repos and time.monotonic() - self._repos_at < self.REPOS_TTL: return self._repos r = self.dev.call("repos") if r.get("ok"): self.set_repos(r) return r def set_repos(self, r: dict) -> None: with self._lock: self._repos, self._repos_at = r, time.monotonic() def page_data(self) -> tuple[dict, dict]: """`list` and (on a cache miss) `repos`, side by side over the shared connection.""" with ThreadPoolExecutor(max_workers=1) as pool: repos = pool.submit(self.repos) listing = self.dev.call("list") return listing, (repos.result() if listing.get("ok") else {}) def add_repo(self, f: dict) -> tuple[dict, str]: add = self.repos().get("add") if not add: return {"ok": False, "error": "adding repos is turned off on the dev box ([repo_add] in config.toml)"}, "" try: owner, repo = parse_repo_input(f.get("url", ""), add["base_url"]) except ValueError as err: return {"ok": False, "error": str(err)}, "" key = f.get("key", "").strip() or key_from_repo(repo) r = self.dev.call("add-repo", key, f"{owner}/{repo}", timeout=60) if r.get("ok"): self.set_repos({"ok": True, "repos": r["repos"], "add": add}) return r, f"Added {key} — it's now in the Repository list" def make_handler(app: App): class Handler(BaseHTTPRequestHandler): server_version = "sessions-web" sys_version = "" def user(self) -> str: return (self.headers.get(app.auth_header) or "").strip() def log_message(self, fmt, *args): 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, cache: str = "no-store"): self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", cache) self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'; connect-src 'self'; " "form-action 'self'; frame-ancestors 'none'; base-uri 'none'") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "no-referrer") for k, v in (headers or {}).items(): self.send_header(k, v) self.end_headers() if self.command != "HEAD": self.wfile.write(body) def refuse_unauthenticated(self) -> bool: """Fail closed if the request didn't come through Authelia. Behind Caddy's forward_auth the header is always set by Authelia (copy_headers overwrites whatever the client sent). If it's missing, the route has lost its forward_auth — don't serve. """ if allowed_user(self.user(), app.allowed_users): return False self.send(403, b"forbidden: this page must be served behind Authelia\n", "text/plain") return True def form(self) -> dict: n = int(self.headers.get("Content-Length") or 0) if n > 4096: return {} return {k: v[0] for k, v in urllib.parse.parse_qs(self.rfile.read(n).decode(errors="replace")).items()} def do_HEAD(self): self.do_GET() def do_GET(self): path = urllib.parse.urlsplit(self.path).path if path == "/healthz": return self.send(200, b"ok\n", "text/plain") if self.refuse_unauthenticated(): return if path in ASSETS: body, ctype = ASSETS[path] return self.send(200, body, ctype, cache="private, max-age=31536000, immutable") if path != "/": return self.send(404, b"not found\n", "text/plain") flash = None q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) if "ok" in q: flash = ("ok", q["ok"][0][:200]) elif "err" in q: flash = ("err", q["err"][0][:300]) listing, repos = app.page_data() self.send(200, dashboard(listing, repos, self.user(), flash)) 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 f = self.form() if path == "/create": args = [" ".join(f.get("name", "").split()), f.get("repo", "")] if f.get("base", "").strip(): args.append(f["base"].strip()) r = app.dev.call("create", *args, timeout=330) done = f"Created {args[0]} — it appears in the Claude app in a few seconds" elif path == "/add-repo": r, done = app.add_repo(f) elif path in DONE: r = app.dev.call(path[1:], f.get("name", "")) done = f"{DONE[path]} {f.get('name', '')}" else: return self.send(404, b"not found\n", "text/plain") self.log_message("%s %s -> %s", path, f.get("name", "") or f.get("url", ""), "ok" if r.get("ok") else r.get("error")) if "application/json" in self.headers.get("Accept", ""): # app.js: answer in place; the page updates without a reload. out = {"ok": True, "message": done} if r.get("ok") else {"ok": False, "error": r.get("error", "failed")} if r.get("ok") and "repos" in r: out["repos"] = r["repos"] return self.send(200, json.dumps(out).encode(), "application/json") key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed")) self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + urllib.parse.urlencode({key: msg})}) return Handler def main(argv: list[str]) -> int: env = dict(os.environ) missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64") if not env.get(k)] if missing: print(f"missing configuration: {', '.join(missing)} (run `sessions-ctl keygen` on the dev box)", file=sys.stderr) return 1 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(":") server = ThreadingHTTPServer((host, int(port)), make_handler(app)) # 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. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) if os.getpid() == 1: # The SSH master connection outlives the call that started it and is # re-parented to PID 1. Python doesn't reap such orphans; an init does. print("warning: running as PID 1; start the container with --init (compose: init: true) " "or exited SSH connections are left as zombies", 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() return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))