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
345 lines
16 KiB
Python
345 lines
16 KiB
Python
#!/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 <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; 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 html
|
||
import json
|
||
import os
|
||
import re
|
||
import shlex
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import urllib.parse
|
||
from http import HTTPStatus
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
||
NAME_CHARS = set("abcdefghijklmnopqrstuvwxyz0123456789-")
|
||
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:
|
||
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
|
||
|
||
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 NAME_CHARS | set("._/") 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",
|
||
"-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)
|
||
|
||
|
||
# ---------------------------------------------------------------- HTML
|
||
|
||
CSS = """
|
||
:root{--bg:#f6f5f2;--fg:#1d1d1b;--muted:#6b6a65;--card:#fff;--line:#e3e1db;--accent:#b4532a;--ok:#2f7d4f;--warn:#a06a00;--bad:#b3261e}
|
||
@media (prefers-color-scheme:dark){:root{--bg:#161615;--fg:#ecebe6;--muted:#9c9a93;--card:#1f1f1d;--line:#34332f;--accent:#e08a5c;--ok:#6cc08f;--warn:#e0b050;--bad:#f08a80}}
|
||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.45 system-ui,-apple-system,sans-serif}
|
||
main{max-width:720px;margin:0 auto;padding:20px 16px 48px}
|
||
header{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin-bottom:16px}
|
||
h1{font-size:1.3rem;margin:0}h2{font-size:1rem;margin:28px 0 10px;color:var(--muted);font-weight:600;text-transform:uppercase;letter-spacing:.04em}
|
||
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:10px}
|
||
.row{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}
|
||
.name{font-weight:600;font-size:1.05rem}.meta{color:var(--muted);font-size:.88rem}
|
||
.pill{font-size:.78rem;padding:2px 8px;border-radius:99px;border:1px solid currentColor}
|
||
.active{color:var(--ok)}.activating,.deactivating{color:var(--warn)}.inactive,.failed,.unknown{color:var(--bad)}
|
||
.actions{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap}
|
||
button,.btn{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--fg);cursor:pointer;text-decoration:none;display:inline-block}
|
||
.primary{background:var(--accent);border-color:var(--accent);color:#fff}
|
||
form.inline{display:inline}label{display:block;font-size:.88rem;color:var(--muted);margin:10px 0 4px}
|
||
input,select{font:inherit;width:100%;padding:9px 10px;border-radius:8px;border:1px solid var(--line);background:var(--bg);color:var(--fg)}
|
||
.flash{padding:10px 14px;border-radius:8px;margin-bottom:14px;border:1px solid}.flash.err{color:var(--bad)}.flash.ok{color:var(--ok)}
|
||
.warn{color:var(--warn);font-size:.9rem;margin-top:6px}a{color:var(--accent)}
|
||
"""
|
||
|
||
|
||
def page(title: str, body: str) -> bytes:
|
||
return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>{html.escape(title)}</title><link rel="stylesheet" href="/app.css"></head>
|
||
<body><main>{body}</main></body></html>""".encode()
|
||
|
||
|
||
def e(v) -> str:
|
||
return html.escape(str(v if v is not None else ""))
|
||
|
||
|
||
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
|
||
parts = [f'<header><h1>Sessions</h1><span class="meta">{e(user)}</span></header>']
|
||
if flash:
|
||
parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>')
|
||
if not listing.get("ok"):
|
||
parts.append(f'<div class="flash err">{e(listing.get("error", "dev box error"))}</div>')
|
||
sessions = listing.get("sessions", [])
|
||
running = sum(1 for s in sessions if s["state"] == "active")
|
||
parts.append(f'<h2>Running {running} of {e(listing.get("max_running", "?"))}</h2>')
|
||
if not sessions and listing.get("ok"):
|
||
parts.append('<p class="meta">No sessions yet.</p>')
|
||
for s in sessions:
|
||
link = (f'<a class="btn primary" href="{e(s["remote_control_url"])}" rel="noopener">Open in Claude</a>'
|
||
if s.get("remote_control_url") and s["state"] == "active" else "")
|
||
verb = "stop" if s["enabled"] else "start"
|
||
warn = f'<div class="warn">⚠ {e(s["needs_attention"])}</div>' if s.get("needs_attention") else ""
|
||
restarts = f' · restarted {e(s["restarts"])}×' if s.get("restarts") else ""
|
||
parts.append(f"""<div class="card"><div class="row"><span class="name">{e(s["name"])}</span>
|
||
<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="actions">{link}<form method="post" action="/{verb}" class="inline">
|
||
<input type="hidden" name="name" value="{e(s["name"])}">
|
||
<button>{verb.title()}</button></form></div></div>""")
|
||
|
||
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">
|
||
<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="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off">
|
||
<div class="actions"><button class="primary">Create</button><a class="btn" href="/">Refresh</a></div></form>
|
||
<p class="meta">A session runs Claude Code on the dev box with Remote Control on. Give it instructions from the Claude app or the “Open in Claude” link — never from this page.</p>""")
|
||
return page("Sessions", "".join(parts))
|
||
|
||
|
||
# ---------------------------------------------------------------- server
|
||
|
||
|
||
class App:
|
||
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()}
|
||
|
||
|
||
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):
|
||
self.send_response(status)
|
||
self.send_header("Content-Type", ctype)
|
||
self.send_header("Content-Length", str(len(body)))
|
||
self.send_header("Cache-Control", "no-store")
|
||
self.send_header("Content-Security-Policy", "default-src 'none'; style-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 == "/app.css":
|
||
return self.send(200, CSS.encode(), "text/css")
|
||
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 = app.dev.call("list")
|
||
repos = app.dev.call("repos") if listing.get("ok") else {}
|
||
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 = [f.get("name", "").strip(), 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 will appear in the Claude app in a few seconds"
|
||
elif path in ("/start", "/stop"):
|
||
r = app.dev.call(path[1:], f.get("name", ""))
|
||
done = {"/start": "started", "/stop": "stopped"}[path] + f" {f.get('name', '')}"
|
||
else:
|
||
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"))
|
||
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))
|
||
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:]))
|