Merge pull request 'Archive sessions, allow spaces in names, stop tripping the SSH rate limit' (#2) from session/archive-and-bugfix into main
Reviewed-on: #2
This commit is contained in:
commit
39997de1e8
7 changed files with 244 additions and 32 deletions
10
AGENTS.md
10
AGENTS.md
|
|
@ -25,8 +25,14 @@ model" before changing anything that touches the SSH boundary.
|
|||
|
||||
## Invariants — do not break
|
||||
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
|
||||
test in `dev/tests/test_sessions_ctl.py`.
|
||||
feature, no free-text arguments. The session title (`TITLE_RE`: letters,
|
||||
digits, `-`, single spaces) is the only argument with a space; it becomes
|
||||
claude's `--name` via `shlex.join` and nothing else. New remote verbs need
|
||||
validation *and* a test in `dev/tests/test_sessions_ctl.py`. Validate with
|
||||
`fullmatch`: `re.match(...$)` accepts a trailing newline.
|
||||
7. The web app reaches the dev box over one multiplexed SSH connection. The
|
||||
dev box's UFW `limit` refuses a 6th connection in 30 s, so don't drop
|
||||
`ControlMaster`, and keep `init: true` so the master gets reaped.
|
||||
2. Local-only verbs (`delete`, `refresh-access`, `keygen`, `_launch`) stay out
|
||||
of `REMOTE_VERBS`.
|
||||
6. The private key is never written to disk on the dev box outside a temp dir
|
||||
|
|
|
|||
17
README.md
17
README.md
|
|
@ -31,8 +31,8 @@ from="<IP of reudy.net>",restrict,command="…/sessions-ctl --remote" ssh-ed2551
|
|||
|
||||
- **`command=`**: whatever prod asks for, sshd runs `sessions-ctl --remote`. It
|
||||
reads `$SSH_ORIGINAL_COMMAND`, splits it without a shell, and accepts only
|
||||
`list repos status create start stop health`. Names and branches are
|
||||
checked against strict patterns; repos are picked by key from an allowlist
|
||||
`list repos status create start stop archive unarchive health`. Names,
|
||||
titles and branches are checked against strict patterns; repos are picked by key from an allowlist
|
||||
in the config, so no URL or path crosses the link.
|
||||
- **`restrict`**: no PTY, no port/agent/X11 forwarding. (Tested: `-L` is refused.)
|
||||
- **`from=`**: the key only works from the address `reudy.net` resolves to.
|
||||
|
|
@ -83,7 +83,11 @@ Claude Code field. If a Claude Code update breaks it, the session shows
|
|||
|
||||
## How a session lives
|
||||
|
||||
- `create NAME REPO [BASE]`: clones the repo into `~/sessions/NAME`, creates
|
||||
- `create TITLE REPO [BASE]`: the title is what you type, e.g. `Fix login bug`
|
||||
(letters, digits, `-` and single spaces, up to 48 chars). The session's NAME
|
||||
is derived from it (`fix-login-bug`) and used for the directory, branch, unit
|
||||
and tmux socket. The title is shown on the page and is the session's name in
|
||||
the Claude app. It clones the repo into `~/sessions/NAME`, creates
|
||||
branch `session/NAME`, writes `~/.local/state/sessions/NAME.json` (with a
|
||||
fixed conversation UUID) and runs `systemctl --user enable --now
|
||||
claude-session@NAME`.
|
||||
|
|
@ -97,6 +101,9 @@ Claude Code field. If a Claude Code update breaks it, the session shows
|
|||
linger on.
|
||||
- **Stop:** `disable --now`, so the session stays stopped across reboots until you
|
||||
start it again.
|
||||
- **Archive:** stops the session and moves it to the page's "Archived" section.
|
||||
The checkout and the conversation are kept; **Unarchive** puts it back in the
|
||||
list, stopped. An archived session can't be started until it's unarchived.
|
||||
- **Limits:** `max_running` in the config (default 2). Each unit has
|
||||
`MemoryHigh=1200M` and `MemoryMax=1600M`, which apply to claude and everything
|
||||
it runs.
|
||||
|
|
@ -151,7 +158,7 @@ file and run:
|
|||
|
||||
```sh
|
||||
podman build -t localhost/sessions-web web/
|
||||
podman run -d --name sessions-web --restart unless-stopped \
|
||||
podman run -d --name sessions-web --restart unless-stopped --init \
|
||||
--env-file ~/.config/sessions-web/env -p 127.0.0.1:8470:8470 \
|
||||
--read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \
|
||||
localhost/sessions-web
|
||||
|
|
@ -176,6 +183,8 @@ sessions.reudy.net {
|
|||
| "forbidden: this page must be served behind Authelia" | The route has no forward_auth, or the user isn't in `SESSIONS_ALLOWED_USERS` |
|
||||
| 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 |
|
||||
| "dev box unreachable: … Connection refused" | The dev box's UFW `limit` rule refuses the 6th new SSH connection from one address within 30 s (`journalctl -k \| grep "UFW LIMIT BLOCK"`). The app reuses one connection (`ControlPersist`), so this needs an unusual burst or a container that can't keep its control socket in `/tmp` |
|
||||
| Container log: "running as PID 1" | Start it with `--init` (compose: `init: true`), otherwise exited SSH master connections pile up as zombies |
|
||||
| "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 |
|
||||
| "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()` |
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ services:
|
|||
build: ./web
|
||||
image: localhost/sessions-web:latest
|
||||
restart: unless-stopped
|
||||
# Reaps the SSH master connection app.py leaves running between calls.
|
||||
init: true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
|
|
|
|||
|
|
@ -56,6 +56,9 @@ UNIT = "claude-session@{}.service"
|
|||
KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys
|
||||
|
||||
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")
|
||||
# What the user typed as the name: letters, digits, single spaces and '-'. The
|
||||
# session's NAME (directory, branch, unit, tmux socket) is derived from it.
|
||||
TITLE_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]| (?! )){0,47}(?<! )$")
|
||||
BRANCH_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$")
|
||||
RC_URL_RE = re.compile(r"https://claude\.ai/code/session_[A-Za-z0-9]+")
|
||||
TRUST_PROMPT = "Yes, I trust this folder"
|
||||
|
|
@ -63,7 +66,7 @@ TRUST_PROMPT = "Yes, I trust this folder"
|
|||
# has "skipDangerousModePermissionPrompt": true.
|
||||
BYPASS_PROMPT = "running in Bypass Permissions mode"
|
||||
|
||||
REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "health"}
|
||||
REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "archive", "unarchive", "health"}
|
||||
|
||||
DEFAULTS = {
|
||||
"workspace_root": "~/sessions",
|
||||
|
|
@ -90,19 +93,27 @@ def load_config(path: Path | None = None) -> dict:
|
|||
cfg["workspace_root"] = Path(os.path.expanduser(cfg["workspace_root"]))
|
||||
cfg["max_running"] = int(cfg["max_running"])
|
||||
for key, url in cfg["repos"].items():
|
||||
if not NAME_RE.match(key) or not isinstance(url, str):
|
||||
if not NAME_RE.fullmatch(key) or not isinstance(url, str):
|
||||
raise UserError(f"config: bad repo entry {key!r}")
|
||||
return cfg
|
||||
|
||||
|
||||
def validate_name(name: str) -> str:
|
||||
if not NAME_RE.match(name):
|
||||
if not NAME_RE.fullmatch(name):
|
||||
raise UserError("name must be 1-32 chars of a-z, 0-9 and '-', starting with a letter or digit")
|
||||
return name
|
||||
|
||||
|
||||
def name_from_title(title: str) -> tuple[str, str]:
|
||||
"""'Fix login bug' -> ('fix-login-bug', 'Fix login bug'). A plain NAME maps to itself."""
|
||||
if not TITLE_RE.fullmatch(title):
|
||||
raise UserError("name must be 1-48 chars of letters, digits, '-' and single spaces")
|
||||
name = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")[:32].rstrip("-")
|
||||
return validate_name(name), title
|
||||
|
||||
|
||||
def validate_branch(branch: str) -> str:
|
||||
if not BRANCH_RE.match(branch) or ".." in branch or branch.endswith((".lock", "/", ".")):
|
||||
if not BRANCH_RE.fullmatch(branch) or ".." in branch or branch.endswith((".lock", "/", ".")):
|
||||
raise UserError("invalid branch name")
|
||||
return branch
|
||||
|
||||
|
|
@ -230,7 +241,8 @@ def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS)
|
|||
approval. See README "Security model" for why that is acceptable here.
|
||||
"""
|
||||
rc_name = f"{prefix}-{state['name']}"
|
||||
args = ["claude", "--dangerously-skip-permissions", "--remote-control", rc_name, "--name", state["name"]]
|
||||
title = state.get("title") or state["name"]
|
||||
args = ["claude", "--dangerously-skip-permissions", "--remote-control", rc_name, "--name", title]
|
||||
if any(projects_dir.glob(f"*/{state['uuid']}.jsonl")):
|
||||
return args + ["--resume", state["uuid"]]
|
||||
return args + ["--session-id", state["uuid"]]
|
||||
|
|
@ -243,6 +255,8 @@ def session_view(state: dict, with_pane: bool = True) -> dict:
|
|||
u = unit_state(state["name"])
|
||||
view = {
|
||||
"name": state["name"],
|
||||
"title": state.get("title") or state["name"],
|
||||
"archived": bool(state.get("archived")),
|
||||
"repo": state["repo"],
|
||||
"branch": state["branch"],
|
||||
"created_at": state["created_at"],
|
||||
|
|
@ -256,8 +270,11 @@ def session_view(state: dict, with_pane: bool = True) -> dict:
|
|||
pane = capture_pane(state["name"])
|
||||
m = RC_URL_RE.search(pane)
|
||||
if m and m.group(0) != state.get("remote_control_url"):
|
||||
state["remote_control_url"] = view["remote_control_url"] = m.group(0)
|
||||
write_state(state)
|
||||
view["remote_control_url"] = m.group(0)
|
||||
with lock(): # re-read so this can't undo a concurrent archive/unarchive
|
||||
fresh = read_state(state["name"])
|
||||
fresh["remote_control_url"] = m.group(0)
|
||||
write_state(fresh)
|
||||
if TRUST_PROMPT in pane:
|
||||
view["needs_attention"] = "stuck on the folder-trust prompt; attach with tmux to accept"
|
||||
elif BYPASS_PROMPT in pane:
|
||||
|
|
@ -281,8 +298,8 @@ def cmd_status(cfg: dict, args: list[str]) -> dict:
|
|||
|
||||
|
||||
def cmd_create(cfg: dict, args: list[str]) -> dict:
|
||||
name, repo, *rest = _arity(args, 2, 3)
|
||||
validate_name(name)
|
||||
title, repo, *rest = _arity(args, 2, 3)
|
||||
name, title = name_from_title(title)
|
||||
if repo not in cfg["repos"]:
|
||||
raise UserError(f"repo {repo!r} is not in the allowlist")
|
||||
base = validate_branch(rest[0]) if rest else None
|
||||
|
|
@ -306,6 +323,7 @@ def cmd_create(cfg: dict, args: list[str]) -> dict:
|
|||
trust_workspace(workspace)
|
||||
state = {
|
||||
"name": name,
|
||||
"title": title,
|
||||
"repo": repo,
|
||||
"base": base,
|
||||
"branch": f"session/{name}",
|
||||
|
|
@ -320,8 +338,11 @@ def cmd_create(cfg: dict, args: list[str]) -> dict:
|
|||
|
||||
def cmd_start(cfg: dict, args: list[str]) -> dict:
|
||||
(name,) = _arity(args, 1, 1)
|
||||
state = read_state(validate_name(name))
|
||||
validate_name(name)
|
||||
with lock():
|
||||
state = read_state(name)
|
||||
if state.get("archived"):
|
||||
raise UserError(f"{name} is archived; unarchive it first")
|
||||
if unit_state(name)["active"] != "active" and running_count() >= cfg["max_running"]:
|
||||
raise UserError(f"limit reached: {cfg['max_running']} sessions already running")
|
||||
systemctl("enable", "--now", UNIT.format(name))
|
||||
|
|
@ -335,6 +356,27 @@ def cmd_stop(cfg: dict, args: list[str]) -> dict:
|
|||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_archive(cfg: dict, args: list[str]) -> dict:
|
||||
"""Stop the session and move it to the archive. Keeps its checkout and conversation."""
|
||||
(name,) = _arity(args, 1, 1)
|
||||
with lock(): # so a concurrent `start` can't slip in between the stop and the flag
|
||||
state = read_state(validate_name(name))
|
||||
systemctl("disable", "--now", UNIT.format(name))
|
||||
state["archived"] = True
|
||||
write_state(state)
|
||||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_unarchive(cfg: dict, args: list[str]) -> dict:
|
||||
"""Back to the normal list, still stopped."""
|
||||
(name,) = _arity(args, 1, 1)
|
||||
with lock():
|
||||
state = read_state(validate_name(name))
|
||||
state.pop("archived", None)
|
||||
write_state(state)
|
||||
return {"session": session_view(state, with_pane=False)}
|
||||
|
||||
|
||||
def cmd_health(cfg: dict, args: list[str]) -> dict:
|
||||
_arity(args, 0, 0)
|
||||
mem = {}
|
||||
|
|
@ -534,6 +576,8 @@ VERBS = {
|
|||
"create": cmd_create,
|
||||
"start": cmd_start,
|
||||
"stop": cmd_stop,
|
||||
"archive": cmd_archive,
|
||||
"unarchive": cmd_unarchive,
|
||||
"health": cmd_health,
|
||||
"delete": cmd_delete,
|
||||
"refresh-access": cmd_refresh_access,
|
||||
|
|
|
|||
|
|
@ -63,6 +63,88 @@ class Validation(unittest.TestCase):
|
|||
sc.cmd_repos({"repos": {}}, ["extra"])
|
||||
|
||||
|
||||
def test_trailing_newline_rejected(self):
|
||||
# re.match + "$" would accept "a\n"; sessions-ctl must use fullmatch.
|
||||
for f, v in ((sc.validate_name, "a\n"), (sc.validate_branch, "main\n"), (sc.name_from_title, "Fix\n")):
|
||||
with self.assertRaises(sc.UserError, msg=repr(v)):
|
||||
f(v)
|
||||
|
||||
def test_titles(self):
|
||||
self.assertEqual(sc.name_from_title("Fix login bug"), ("fix-login-bug", "Fix login bug"))
|
||||
self.assertEqual(sc.name_from_title("fix-login"), ("fix-login", "fix-login"))
|
||||
self.assertEqual(sc.name_from_title("a - b"), ("a-b", "a - b"))
|
||||
self.assertEqual(sc.name_from_title("X" * 48)[0], "x" * 32)
|
||||
for bad in ("", " a", "a ", "a b", "X" * 49, "a_b", "-a", "a\tb", "a;b", "$(id)", "---", "'a'"):
|
||||
with self.assertRaises(sc.UserError, msg=bad):
|
||||
sc.name_from_title(bad)
|
||||
|
||||
def test_title_survives_the_ssh_round_trip(self):
|
||||
import shlex
|
||||
self.assertEqual(sc.parse_remote(shlex.join(["create", "Fix login bug", "papure"])),
|
||||
["create", "Fix login bug", "papure"])
|
||||
|
||||
|
||||
class Archive(unittest.TestCase):
|
||||
"""archive/unarchive with systemd stubbed out and state in a temp dir."""
|
||||
|
||||
def setUp(self):
|
||||
from unittest import mock
|
||||
d = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(d.cleanup)
|
||||
self.calls = []
|
||||
self.active = set()
|
||||
|
||||
def systemctl(*args, check=True):
|
||||
self.calls.append(args)
|
||||
if args[:2] == ("disable", "--now"):
|
||||
self.active.discard(args[2])
|
||||
elif args[:2] == ("enable", "--now"):
|
||||
self.active.add(args[2])
|
||||
|
||||
def unit_state(name):
|
||||
on = sc.UNIT.format(name) in self.active
|
||||
return {"active": "active" if on else "inactive", "sub": "", "enabled": on, "restarts": 0}
|
||||
|
||||
for target, value in (("STATE_DIR", Path(d.name)), ("systemctl", systemctl), ("unit_state", unit_state)):
|
||||
p = mock.patch.object(sc, target, value)
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
sc.write_state({"name": "s1", "title": "S 1", "repo": "r", "branch": "session/s1",
|
||||
"workspace": "/nonexistent", "uuid": "u", "created_at": "2026-10-06T00:00:00+00:00"})
|
||||
self.active.add(sc.UNIT.format("s1"))
|
||||
self.cfg = {"max_running": 2}
|
||||
|
||||
def test_archive_stops_and_flags(self):
|
||||
view = sc.cmd_archive(self.cfg, ["s1"])["session"]
|
||||
self.assertIn(("disable", "--now", "claude-session@s1.service"), self.calls)
|
||||
self.assertTrue(view["archived"])
|
||||
self.assertEqual(view["state"], "inactive")
|
||||
self.assertEqual(view["title"], "S 1")
|
||||
self.assertTrue(sc.read_state("s1")["archived"])
|
||||
|
||||
def test_archived_cannot_start_until_unarchived(self):
|
||||
sc.cmd_archive(self.cfg, ["s1"])
|
||||
with self.assertRaises(sc.UserError):
|
||||
sc.cmd_start(self.cfg, ["s1"])
|
||||
view = sc.cmd_unarchive(self.cfg, ["s1"])["session"]
|
||||
self.assertFalse(view["archived"])
|
||||
self.assertEqual(view["state"], "inactive") # unarchive doesn't start it
|
||||
sc.cmd_start(self.cfg, ["s1"])
|
||||
self.assertEqual(sc.unit_state("s1")["active"], "active")
|
||||
|
||||
def test_validates_name(self):
|
||||
for verb in (sc.cmd_archive, sc.cmd_unarchive):
|
||||
for bad in ("../x", "$(id)", "nope"):
|
||||
with self.assertRaises(sc.UserError, msg=bad):
|
||||
verb(self.cfg, [bad])
|
||||
with self.assertRaises(sc.UserError):
|
||||
verb(self.cfg, ["s1", "extra"])
|
||||
|
||||
def test_remote_verbs(self):
|
||||
self.assertEqual(sc.parse_remote("archive s1"), ["archive", "s1"])
|
||||
self.assertEqual(sc.parse_remote("unarchive s1"), ["unarchive", "s1"])
|
||||
|
||||
|
||||
class AuthorizedKeys(unittest.TestCase):
|
||||
def test_line_shape(self):
|
||||
line = sc.authorized_line(KEY, ["37.205.10.63"], "/home/agent/.local/bin/sessions-ctl")
|
||||
|
|
@ -117,6 +199,11 @@ class ClaudeArgs(unittest.TestCase):
|
|||
self.assertEqual(resumed[-2:], ["--resume", state["uuid"]])
|
||||
self.assertIn("--dangerously-skip-permissions", resumed)
|
||||
|
||||
def test_title_is_the_claude_name(self):
|
||||
args = sc.claude_args({"name": "s1", "title": "Fix login bug", "uuid": "u"}, "dev-box", Path("/nonexistent"))
|
||||
self.assertEqual(args[args.index("--name") + 1], "Fix login bug")
|
||||
self.assertEqual(args[args.index("--remote-control") + 1], "dev-box-s1")
|
||||
|
||||
|
||||
class MainContract(unittest.TestCase):
|
||||
def test_remote_without_command_prints_json_error(self):
|
||||
|
|
|
|||
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