Archive sessions, allow spaces in names, stop tripping the SSH rate limit
Connection refused: the dev box's UFW `limit` rule refuses the 6th new SSH connection from one address within 30 s. Every page view made two calls (list, repos) and every button one more, so stopping two sessions and refreshing hit it (kernel log: "UFW LIMIT BLOCK" from prod's IP). The web app now multiplexes all calls over one connection (ControlMaster=auto, ControlPersist=120), with the socket in its private temp dir. compose.yaml gets `init: true` so the backgrounded master is reaped; the app warns if it runs as PID 1. Spaces in names: `create` now takes a title (letters, digits, '-', single spaces, <= 48 chars). The slug used for the directory, branch, unit and tmux socket is derived from it; the title is shown on the page and passed to claude as --name. A plain slug still maps to itself. Archive: new remote verbs `archive` (stop + flag, keeps checkout and conversation) and `unarchive` (back to the list, still stopped). An archived session refuses `start`. The page lists archived sessions in a collapsible section. `list` re-reads state under the lock before saving a Remote Control URL so it can't undo a concurrent archive. Also: name/branch validation used re.match with `$`, which accepts a trailing newline; it now uses fullmatch. Tested end to end with a throwaway 127.0.0.1 key and the real container: 24 remote calls went over 1 TCP connection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rog8S9b5qKaw6nUicxXLkM
This commit is contained in:
parent
2569937fa7
commit
0738171f1e
7 changed files with 244 additions and 32 deletions
70
web/app.py
70
web/app.py
|
|
@ -37,7 +37,10 @@ import urllib.parse
|
|||
from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
NAME_CHARS = set("abcdefghijklmnopqrstuvwxyz0123456789-")
|
||||
# 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+/=]+$")
|
||||
|
||||
|
||||
|
|
@ -80,16 +83,28 @@ def materialise_ssh_files(env: dict, directory: str) -> tuple[str, str]:
|
|||
|
||||
|
||||
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 NAME_CHARS | set("._/") for c in a) or a.startswith("-"):
|
||||
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",
|
||||
|
|
@ -101,6 +116,9 @@ class DevBox:
|
|||
"-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,
|
||||
|
|
@ -167,6 +185,9 @@ form.inline{display:inline}label{display:block;font-size:.88rem;color:var(--mute
|
|||
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)}
|
||||
details>summary{cursor:pointer;list-style:none}details>summary::-webkit-details-marker{display:none}
|
||||
details>summary h2::before{content:"▸ "}details[open]>summary h2::before{content:"▾ "}
|
||||
.card.archived{opacity:.75}
|
||||
"""
|
||||
|
||||
|
||||
|
|
@ -181,13 +202,28 @@ def e(v) -> str:
|
|||
return html.escape(str(v if v is not None else ""))
|
||||
|
||||
|
||||
def action(verb: str, name: str) -> str:
|
||||
return (f'<form method="post" action="/{verb}" class="inline">'
|
||||
f'<input type="hidden" name="name" value="{e(name)}"><button>{verb.title()}</button></form>')
|
||||
|
||||
|
||||
def session_card(s: dict, actions: str, cls: str = "") -> str:
|
||||
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 ""
|
||||
return f"""<div class="card {cls}"><div class="row"><span class="name">{e(s.get("title") or 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">{actions}</div></div>"""
|
||||
|
||||
|
||||
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", [])
|
||||
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'<h2>Running {running} of {e(listing.get("max_running", "?"))}</h2>')
|
||||
if not sessions and listing.get("ok"):
|
||||
|
|
@ -196,18 +232,14 @@ def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | No
|
|||
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>""")
|
||||
parts.append(session_card(s, link + action(verb, s["name"]) + action("archive", s["name"])))
|
||||
if archived:
|
||||
cards = "".join(session_card(s, action("unarchive", s["name"]), "archived") for s in archived)
|
||||
parts.append(f'<details><summary><h2>Archived ({len(archived)})</h2></summary>{cards}</details>')
|
||||
|
||||
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="name">Name</label><input id="name" name="name" required maxlength="48" pattern="[A-Za-z0-9][A-Za-z0-9 \\-]{{0,47}}" placeholder="Fix login bug" 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>
|
||||
|
|
@ -217,6 +249,9 @@ def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | No
|
|||
|
||||
# ---------------------------------------------------------------- server
|
||||
|
||||
# Buttons that take just a session name, and what the page says afterwards.
|
||||
DONE = {"/start": "started", "/stop": "stopped", "/archive": "stopped and archived", "/unarchive": "unarchived"}
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, env: dict, dev: DevBox):
|
||||
|
|
@ -299,14 +334,14 @@ def make_handler(app: App):
|
|||
path = urllib.parse.urlsplit(self.path).path
|
||||
f = self.form()
|
||||
if path == "/create":
|
||||
args = [f.get("name", "").strip(), f.get("repo", "")]
|
||||
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 will appear in the Claude app in a few seconds"
|
||||
elif path in ("/start", "/stop"):
|
||||
elif path in DONE:
|
||||
r = app.dev.call(path[1:], f.get("name", ""))
|
||||
done = {"/start": "started", "/stop": "stopped"}[path] + f" {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", ""), "ok" if r.get("ok") else r.get("error"))
|
||||
|
|
@ -334,6 +369,11 @@ def main(argv: list[str]) -> int:
|
|||
# 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)
|
||||
|
|
|
|||
|
|
@ -68,14 +68,38 @@ class SshArgv(unittest.TestCase):
|
|||
self.assertIn("UserKnownHostsFile=/kh", argv)
|
||||
self.assertEqual(argv[-2:], ["--", "create fix-login papure feature/x"])
|
||||
|
||||
def test_multiplexes_over_one_connection(self):
|
||||
argv = self.dev.argv("list")
|
||||
self.assertIn("ControlMaster=auto", argv)
|
||||
self.assertIn("ControlPath=/cm-%C", argv) # next to the key, in the private temp dir
|
||||
|
||||
def test_title_with_spaces_is_one_quoted_argument(self):
|
||||
self.assertEqual(self.dev.argv("create", "Fix login bug", "papure")[-1], "create 'Fix login bug' papure")
|
||||
|
||||
def test_rejects_odd_arguments(self):
|
||||
for bad in ("", "-oProxyCommand=x", "a b", "$(id)", "a;b", "A"):
|
||||
for bad in ("", "-oProxyCommand=x", " -x", "$(id)", "a;b", "a\nb", "a\tb", "'a'", "a`b`"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
self.dev.argv("status", bad)
|
||||
self.assertFalse(self.dev.call("status", "a;b")["ok"])
|
||||
|
||||
|
||||
class Rendering(unittest.TestCase):
|
||||
def test_archived_section(self):
|
||||
def s(name, archived):
|
||||
return {"name": name, "title": name.upper(), "archived": archived, "repo": "r", "branch": "b",
|
||||
"created_at": "2026-10-06T00:00:00", "state": "inactive", "enabled": False, "restarts": 0}
|
||||
out = app.dashboard({"ok": True, "max_running": 2, "sessions": [s("live", False), s("old", True)]},
|
||||
{"repos": []}, "u", None).decode()
|
||||
live, archived = out.split("<details>")
|
||||
self.assertIn("LIVE", live)
|
||||
self.assertIn('action="/archive"', live)
|
||||
self.assertNotIn("OLD", live)
|
||||
self.assertIn("Archived (1)", archived)
|
||||
self.assertIn('action="/unarchive"', archived)
|
||||
self.assertNotIn('action="/start"', archived)
|
||||
no_archive = app.dashboard({"ok": True, "max_running": 2, "sessions": [s("live", False)]}, {}, "u", None)
|
||||
self.assertNotIn(b"<details>", no_archive)
|
||||
|
||||
def test_escapes_everything(self):
|
||||
listing = {"ok": True, "max_running": 2, "sessions": [{
|
||||
"name": "<script>", "repo": "r", "branch": "b", "created_at": "2026-09-30T11:00:00",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue