Add sessions-ctl and systemd units for the dev box

sessions-ctl creates, starts, stops and lists Claude Code sessions. Each one
is a checkout in ~/sessions/<name>, a state file and a systemd user unit that
runs claude with Remote Control in its own tmux server. Sessions are restarted
if they crash, come back at boot (linger), and resume the same conversation
by a pinned session UUID.

Over SSH it runs as a forced command: only list/repos/status/create/start/
stop/health are accepted, arguments are validated, and nothing reaches a shell
or Claude as a prompt. refresh-access keeps the key's from= restriction in
sync with the IP of reudy.net (hourly timer).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
agent 2026-09-30 11:55:38 +00:00
commit 1816f6f863
7 changed files with 754 additions and 0 deletions

25
dev/config.example.toml Normal file
View file

@ -0,0 +1,25 @@
# ~/.config/sessions/config.toml — read by sessions-ctl. chmod 600.
# install.sh copies this file there once and never overwrites it.
# Where session checkouts live (one directory per session).
workspace_root = "~/sessions"
# How many sessions may run at once. Each claude process takes a few hundred
# MB; the unit caps each session at 1.6 GB (MemoryMax). The box has ~4 GB.
max_running = 2
# Remote Control names look like "<prefix>-<session name>" in the Claude app.
remote_control_prefix = "dev-box"
# Repos a session may be created from. The key is what the web app shows and
# sends; the URL never crosses the SSH link. Being on this list is what makes
# a checkout trusted by Claude Code, so only list repos you trust.
[repos]
sessions = "ssh://git@git.reudy.net:14922/reudy-net/sessions.git"
[ssh_access]
# prod's key may only connect from the address(es) this name resolves to.
# Re-resolved hourly by sessions-access-refresh.timer.
allow_from_host = "reudy.net"
# The public half of the key the web app container uses.
public_key = "ssh-ed25519 AAAA… comment"

46
dev/install.sh Executable file
View file

@ -0,0 +1,46 @@
#!/usr/bin/env bash
# Install / update the dev-box side of the session manager for the current user.
# Idempotent: safe to re-run after every pull. Never overwrites config.toml.
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
bin="$HOME/.local/bin"
units="$HOME/.config/systemd/user"
cfg_dir="$HOME/.config/sessions"
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
for cmd in python3 tmux git systemctl claude; do
command -v "$cmd" >/dev/null || PATH="$bin:$PATH" command -v "$cmd" >/dev/null \
|| { echo "missing dependency: $cmd" >&2; exit 1; }
done
python3 -c 'import sys; sys.exit(sys.version_info < (3, 11))' \
|| { echo "python3 >= 3.11 required (tomllib)" >&2; exit 1; }
install -D -m 755 "$here/sessions_ctl.py" "$bin/sessions-ctl"
install -d -m 700 "$cfg_dir" "$HOME/.local/state/sessions"
for f in "$here"/systemd/*; do
install -D -m 644 "$f" "$units/$(basename "$f")"
done
if [[ ! -e "$cfg_dir/config.toml" ]]; then
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."
fi
chmod 600 "$cfg_dir/config.toml"
systemctl --user daemon-reload
systemctl --user enable --now sessions-access-refresh.timer >/dev/null
# Without linger, user units stop at logout and never start at boot.
if [[ "$(loginctl show-user "$USER" -p Linger --value 2>/dev/null)" != "yes" ]]; then
echo "WARNING: linger is off — sessions will not survive a reboot."
echo " run: sudo loginctl enable-linger $USER"
fi
# Write/refresh prod's authorized_keys line if the config has a real key.
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
else
echo "ssh_access.public_key not set yet — skipping authorized_keys."
fi
echo "installed. try: sessions-ctl health"

501
dev/sessions_ctl.py Executable file
View file

@ -0,0 +1,501 @@
#!/usr/bin/env python3
"""sessions-ctl — create, list, start and stop Claude Code sessions on this box.
Two ways in:
* Locally: sessions-ctl <verb> [args] (all verbs)
* Over SSH: sessions-ctl --remote (forced command in authorized_keys)
The requested command is read from $SSH_ORIGINAL_COMMAND and only
REMOTE_VERBS are accepted. Nothing sent over SSH is ever passed to a
shell or to Claude as a prompt — see README "Security model".
Each session is:
* a git checkout in <workspace_root>/<name> on branch session/<name>
* a state file ~/.local/state/sessions/<name>.json (repo, uuid, …)
* a systemd user unit claude-session@<name>.service that runs `claude` with
Remote Control inside its own tmux server (socket: tmux -L claude-<name>).
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.
Output is always one JSON object on stdout. Exit codes: 0 ok, 1 error, 2 usage.
Standard library only, so it runs with the system python3.
"""
from __future__ import annotations
import datetime as dt
import fcntl
import json
import os
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import tomllib
import uuid
from contextlib import contextmanager
from pathlib import Path
HOME = Path.home()
CONFIG_PATH = Path(os.environ.get("SESSIONS_CONFIG", HOME / ".config/sessions/config.toml"))
STATE_DIR = Path(os.environ.get("SESSIONS_STATE_DIR", HOME / ".local/state/sessions"))
CLAUDE_JSON = Path(os.environ.get("SESSIONS_CLAUDE_JSON", HOME / ".claude.json"))
CLAUDE_PROJECTS = HOME / ".claude/projects"
AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys"))
SELF_PATH = HOME / ".local/bin/sessions-ctl"
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}$")
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"
REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "health"}
DEFAULTS = {
"workspace_root": "~/sessions",
"max_running": 2,
"remote_control_prefix": socket.gethostname(),
"repos": {},
"ssh_access": {},
}
class UserError(Exception):
"""A problem the caller can fix (bad name, unknown repo, limit reached…)."""
# ---------------------------------------------------------------- config/state
def load_config(path: Path = CONFIG_PATH) -> dict:
cfg = dict(DEFAULTS)
if path.exists():
with path.open("rb") as f:
cfg.update(tomllib.load(f))
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):
raise UserError(f"config: bad repo entry {key!r}")
return cfg
def validate_name(name: str) -> str:
if not NAME_RE.match(name):
raise UserError("name must be 1-32 chars of a-z, 0-9 and '-', starting with a letter or digit")
return name
def validate_branch(branch: str) -> str:
if not BRANCH_RE.match(branch) or ".." in branch or branch.endswith((".lock", "/", ".")):
raise UserError("invalid branch name")
return branch
def state_path(name: str) -> Path:
return STATE_DIR / f"{name}.json"
def read_state(name: str) -> dict:
p = state_path(name)
if not p.exists():
raise UserError(f"no session named {name!r}")
return json.loads(p.read_text())
def atomic_write(path: Path, text: str, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
try:
with os.fdopen(fd, "w") as f:
f.write(text)
os.chmod(tmp, mode)
os.replace(tmp, path)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raise
def write_state(state: dict) -> None:
atomic_write(state_path(state["name"]), json.dumps(state, indent=2) + "\n")
def all_states() -> list[dict]:
if not STATE_DIR.exists():
return []
return [json.loads(p.read_text()) for p in sorted(STATE_DIR.glob("*.json"))]
@contextmanager
def lock():
"""Serialise create/start so two requests can't both slip under max_running."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_DIR / ".lock", "w") as f:
fcntl.flock(f, fcntl.LOCK_EX)
yield
# ---------------------------------------------------------------- systemd/tmux
def _user_env() -> dict:
"""systemctl --user needs XDG_RUNTIME_DIR; an SSH forced command may lack it."""
env = dict(os.environ)
env.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
return env
def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess:
r = subprocess.run(["systemctl", "--user", *args], capture_output=True, text=True, env=_user_env(), timeout=60)
if check and r.returncode != 0:
raise RuntimeError(f"systemctl {' '.join(args)}: {r.stderr.strip()}")
return r
def unit_state(name: str) -> dict:
r = systemctl("show", UNIT.format(name), "-p", "ActiveState", "-p", "SubState", "-p", "UnitFileState", "-p", "NRestarts", check=False)
props = dict(line.split("=", 1) for line in r.stdout.splitlines() if "=" in line)
return {
"active": props.get("ActiveState", "unknown"),
"sub": props.get("SubState", "unknown"),
"enabled": props.get("UnitFileState") == "enabled",
"restarts": int(props.get("NRestarts") or 0),
}
def tmux_socket(name: str) -> str:
return f"claude-{name}"
def capture_pane(name: str) -> str:
r = subprocess.run(
["tmux", "-L", tmux_socket(name), "capture-pane", "-p", "-S", "-300", "-t", f"={name}:"],
capture_output=True, text=True, timeout=10,
)
return r.stdout if r.returncode == 0 else ""
def running_count() -> int:
return sum(1 for s in all_states() if unit_state(s["name"])["active"] in ("active", "activating", "reloading"))
# ---------------------------------------------------------------- claude trust
def trust_workspace(path: Path, claude_json: Path = CLAUDE_JSON) -> None:
"""Pre-accept Claude Code's "do you trust this folder?" prompt for `path`.
An unattended session would otherwise sit on that prompt forever. The repo
allowlist in config.toml *is* the trust decision, so recording it here is
equivalent to the admin clicking "Yes". The file is shared with running
claude processes, so the update is a fast read-modify-rename.
"""
data = json.loads(claude_json.read_text()) if claude_json.exists() else {}
projects = data.setdefault("projects", {})
entry = projects.setdefault(str(path), {})
if entry.get("hasTrustDialogAccepted") is True:
return
entry["hasTrustDialogAccepted"] = True
mode = claude_json.stat().st_mode & 0o777 if claude_json.exists() else 0o600
atomic_write(claude_json, json.dumps(data, indent=2), mode)
def untrust_workspace(path: Path, claude_json: Path = CLAUDE_JSON) -> None:
if not claude_json.exists():
return
data = json.loads(claude_json.read_text())
if data.get("projects", {}).pop(str(path), None) is not None:
atomic_write(claude_json, json.dumps(data, indent=2), claude_json.stat().st_mode & 0o777)
def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS) -> list[str]:
"""First launch pins the conversation id; every later launch resumes it."""
rc_name = f"{prefix}-{state['name']}"
args = ["claude", "--remote-control", rc_name, "--name", state["name"]]
if any(projects_dir.glob(f"*/{state['uuid']}.jsonl")):
return args + ["--resume", state["uuid"]]
return args + ["--session-id", state["uuid"]]
# ---------------------------------------------------------------- verbs
def session_view(state: dict, with_pane: bool = True) -> dict:
u = unit_state(state["name"])
view = {
"name": state["name"],
"repo": state["repo"],
"branch": state["branch"],
"created_at": state["created_at"],
"state": u["active"],
"enabled": u["enabled"],
"restarts": u["restarts"],
"remote_control_url": state.get("remote_control_url"),
"needs_attention": None,
}
if with_pane and u["active"] == "active":
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)
if TRUST_PROMPT in pane:
view["needs_attention"] = "stuck on the folder-trust prompt; attach with tmux to accept"
return view
def cmd_list(cfg: dict, args: list[str]) -> dict:
_arity(args, 0, 0)
return {"sessions": [session_view(s) for s in all_states()], "max_running": cfg["max_running"]}
def cmd_repos(cfg: dict, args: list[str]) -> dict:
_arity(args, 0, 0)
return {"repos": sorted(cfg["repos"])}
def cmd_status(cfg: dict, args: list[str]) -> dict:
(name,) = _arity(args, 1, 1)
return {"session": session_view(read_state(validate_name(name)))}
def cmd_create(cfg: dict, args: list[str]) -> dict:
name, repo, *rest = _arity(args, 2, 3)
validate_name(name)
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
workspace = cfg["workspace_root"] / name
with lock():
if state_path(name).exists() or workspace.exists():
raise UserError(f"session {name!r} already exists")
if running_count() >= cfg["max_running"]:
raise UserError(f"limit reached: {cfg['max_running']} sessions already running")
workspace.parent.mkdir(parents=True, exist_ok=True)
clone = ["git", "clone", "--quiet"] + (["--branch", base] if base else []) + ["--", cfg["repos"][repo], str(workspace)]
try:
_run(clone, timeout=300)
_run(["git", "-C", str(workspace), "switch", "--quiet", "-c", f"session/{name}"])
except Exception:
# Only ever removes the directory this call just created.
shutil.rmtree(workspace, ignore_errors=True)
raise
trust_workspace(workspace)
state = {
"name": name,
"repo": repo,
"base": base,
"branch": f"session/{name}",
"workspace": str(workspace),
"uuid": str(uuid.uuid4()),
"created_at": dt.datetime.now(dt.UTC).isoformat(timespec="seconds"),
}
write_state(state)
systemctl("enable", "--now", UNIT.format(name))
return {"session": session_view(state, with_pane=False)}
def cmd_start(cfg: dict, args: list[str]) -> dict:
(name,) = _arity(args, 1, 1)
state = read_state(validate_name(name))
with lock():
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))
return {"session": session_view(state, with_pane=False)}
def cmd_stop(cfg: dict, args: list[str]) -> dict:
(name,) = _arity(args, 1, 1)
state = read_state(validate_name(name))
systemctl("disable", "--now", UNIT.format(name))
return {"session": session_view(state, with_pane=False)}
def cmd_health(cfg: dict, args: list[str]) -> dict:
_arity(args, 0, 0)
mem = {}
for line in Path("/proc/meminfo").read_text().splitlines():
k, v = line.split(":", 1)
if k in ("MemTotal", "MemAvailable"):
mem[k] = int(v.split()[0]) // 1024
return {
"host": socket.gethostname(),
"running": running_count(),
"max_running": cfg["max_running"],
"load": round(os.getloadavg()[0], 2),
"mem_total_mb": mem.get("MemTotal"),
"mem_available_mb": mem.get("MemAvailable"),
}
def cmd_delete(cfg: dict, args: list[str]) -> dict:
"""Local only. Removes a stopped session's checkout. Refuses to lose work."""
force = "--force" in args
names = [a for a in args if a not in ("--force", "--yes")]
if "--yes" not in args or len(names) != 1:
raise UserError("usage: sessions-ctl delete NAME --yes [--force]")
state = read_state(validate_name(names[0]))
if unit_state(state["name"])["active"] == "active":
raise UserError("stop the session first")
ws = Path(state["workspace"])
if ws.exists() and not force:
dirty = _run(["git", "-C", str(ws), "status", "--porcelain"]).stdout.strip()
unpushed = _run(["git", "-C", str(ws), "log", "--oneline", "--branches", "--not", "--remotes"]).stdout.strip()
if dirty or unpushed:
raise UserError("checkout has uncommitted or unpushed work; push it or pass --force")
systemctl("disable", UNIT.format(state["name"]), check=False)
if ws.exists():
shutil.rmtree(ws)
untrust_workspace(ws)
state_path(state["name"]).unlink()
return {"deleted": state["name"]}
def cmd_launch(cfg: dict, args: list[str]) -> dict:
"""ExecStart of claude-session@.service — not callable remotely."""
(name,) = _arity(args, 1, 1)
state = read_state(validate_name(name))
ws = Path(state["workspace"])
if not ws.is_dir():
raise UserError(f"workspace {ws} is missing")
trust_workspace(ws) # re-assert: cheap, and survives a reset ~/.claude.json
sock = tmux_socket(name)
cmd = shlex.join(claude_args(state, cfg["remote_control_prefix"]))
_run(["tmux", "-L", sock, "new-session", "-d", "-s", name, "-x", "200", "-y", "50", "-c", str(ws), cmd])
pid = _run(["tmux", "-L", sock, "display-message", "-p", "#{pid}"]).stdout.strip()
runtime = Path(_user_env()["XDG_RUNTIME_DIR"]) / "claude-session"
runtime.mkdir(parents=True, exist_ok=True)
(runtime / f"{name}.pid").write_text(pid + "\n")
return {"launched": name, "tmux_pid": int(pid)}
def cmd_refresh_access(cfg: dict, args: list[str]) -> dict:
"""Re-resolve ssh_access.allow_from_host and rewrite our authorized_keys line."""
_arity(args, 0, 0)
access = cfg["ssh_access"]
host, pubkey = access.get("allow_from_host"), access.get("public_key")
if not host or not pubkey:
raise UserError("config: ssh_access.allow_from_host and ssh_access.public_key are required")
ips = resolve(host)
if not ips:
# Never write an empty from= (that would lock prod out) — keep the old line.
raise UserError(f"could not resolve {host}; authorized_keys left unchanged")
line = authorized_line(pubkey, ips, str(SELF_PATH))
old = AUTHORIZED_KEYS.read_text() if AUTHORIZED_KEYS.exists() else ""
new = replace_marked_line(old, line)
changed = new != old
if changed:
atomic_write(AUTHORIZED_KEYS, new, 0o600)
return {"changed": changed, "from": ips}
# ---------------------------------------------------------------- helpers
def resolve(host: str) -> list[str]:
try:
infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)
except socket.gaierror:
return []
return sorted({i[4][0] for i in infos})
def authorized_line(pubkey: str, ips: list[str], command: str) -> str:
parts = pubkey.split()
if len(parts) < 2 or not parts[0].startswith("ssh-") or not re.fullmatch(r"[A-Za-z0-9+/=]+", parts[1]):
raise UserError("config: ssh_access.public_key is not an OpenSSH public key")
for ip in ips:
if not re.fullmatch(r"[0-9a-fA-F:.]+", ip):
raise UserError(f"refusing odd address {ip!r}")
return f'from="{",".join(ips)}",restrict,command="{command} --remote" {parts[0]} {parts[1]} {KEY_MARKER}'
def replace_marked_line(text: str, line: str) -> str:
"""Replace the line tagged KEY_MARKER (or append one); leave every other line alone."""
kept = [l for l in text.splitlines() if not l.rstrip().endswith(" " + KEY_MARKER)]
return "\n".join(kept + [line]) + "\n"
def _arity(args: list[str], lo: int, hi: int) -> list[str]:
if not lo <= len(args) <= hi:
raise UserError("wrong number of arguments")
return args
def _run(cmd: list[str], timeout: int = 60) -> subprocess.CompletedProcess:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
if r.returncode != 0:
raise RuntimeError(f"{cmd[0]} failed: {r.stderr.strip()[:500]}")
return r
VERBS = {
"list": cmd_list,
"repos": cmd_repos,
"status": cmd_status,
"create": cmd_create,
"start": cmd_start,
"stop": cmd_stop,
"health": cmd_health,
"delete": cmd_delete,
"refresh-access": cmd_refresh_access,
"_launch": cmd_launch,
}
def parse_remote(original: str | None) -> list[str]:
"""Turn $SSH_ORIGINAL_COMMAND into argv, allowing only REMOTE_VERBS."""
if not original:
raise UserError("interactive login is not allowed; send a command")
try:
argv = shlex.split(original)
except ValueError:
raise UserError("could not parse command")
if not argv or argv[0] not in REMOTE_VERBS:
raise UserError(f"verb not allowed; use one of: {', '.join(sorted(REMOTE_VERBS))}")
return argv
def log(msg: str) -> None:
try:
import syslog
syslog.openlog("sessions-ctl")
syslog.syslog(msg)
except Exception:
pass
def main(argv: list[str]) -> int:
remote = argv[:1] == ["--remote"]
try:
if remote:
argv = parse_remote(os.environ.get("SSH_ORIGINAL_COMMAND"))
log(f"remote from {os.environ.get('SSH_CLIENT', '?').split(' ')[0]}: {shlex.join(argv)}")
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('_'))}}} …")
result = VERBS[argv[0]](load_config(), argv[1:])
print(json.dumps({"ok": True, **result}))
return 0
except UserError as e:
print(json.dumps({"ok": False, "error": str(e)}))
if remote:
log(f"remote rejected: {e}")
return 2 if "usage" in str(e) else 1
except Exception as e: # keep the one-JSON-object contract even on bugs
log(f"error: {e!r}")
print(json.dumps({"ok": False, "error": f"internal error: {e}"}))
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View file

@ -0,0 +1,32 @@
# One Claude Code session with Remote Control, inside its own tmux server.
# Managed by sessions-ctl: `enable --now` = run now and at every boot,
# `disable --now` = stop and stay stopped. Needs linger for boot start.
[Unit]
Description=Claude Code session %i
After=network-online.target
Wants=network-online.target
# Give up after 5 crashes in 10 minutes instead of looping forever.
StartLimitIntervalSec=600
StartLimitBurst=5
[Service]
Type=forking
# systemd user units get a bare environment; claude lives in ~/.local/bin.
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
# tmux (built with systemd support) moves every pane into its own
# tmux-spawn-*.scope over the user D-Bus, which would take claude out of this
# unit's cgroup — escaping MemoryMax and a clean stop. With no bus to reach,
# the move fails harmlessly and claude stays here. Nothing in a session needs D-Bus.
Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/nonexistent
ExecStart=%h/.local/bin/sessions-ctl _launch %i
PIDFile=%t/claude-session/%i.pid
ExecStop=/usr/bin/tmux -L claude-%i kill-server
Restart=always
RestartSec=10
TimeoutStartSec=60
# The box has ~4 GB; keep one runaway session from taking the rest down.
MemoryHigh=1200M
MemoryMax=1600M
[Install]
WantedBy=default.target

View file

@ -0,0 +1,10 @@
# Re-resolve ssh_access.allow_from_host (e.g. reudy.net) and update the
# from="…" restriction on prod's key in ~/.ssh/authorized_keys if the IP moved.
[Unit]
Description=Refresh the source-IP restriction on the session-manager SSH key
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=%h/.local/bin/sessions-ctl refresh-access

View file

@ -0,0 +1,10 @@
[Unit]
Description=Hourly refresh of the session-manager SSH key source IP
[Timer]
OnBootSec=2min
OnUnitActiveSec=1h
Persistent=true
[Install]
WantedBy=timers.target

View file

@ -0,0 +1,130 @@
"""Unit tests for the parts of sessions-ctl that guard the SSH boundary.
Run: python3 -m unittest discover -s dev/tests
"""
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path
_spec = importlib.util.spec_from_file_location("sessions_ctl", Path(__file__).parents[1] / "sessions_ctl.py")
sc = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(sc)
KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPAP6gemgKZVguFi6Diif+dBbMAZQupimeV9OQuUotlw vps-manual"
class RemoteParsing(unittest.TestCase):
def test_allowed_verbs_pass(self):
self.assertEqual(sc.parse_remote("create fix-login papure main"), ["create", "fix-login", "papure", "main"])
self.assertEqual(sc.parse_remote("list"), ["list"])
def test_local_only_verbs_rejected(self):
for cmd in ("delete x --yes --force", "refresh-access", "_launch x"):
with self.assertRaises(sc.UserError, msg=cmd):
sc.parse_remote(cmd)
def test_no_command_means_no_shell(self):
for cmd in (None, "", " "):
with self.assertRaises(sc.UserError):
sc.parse_remote(cmd)
def test_shell_metacharacters_are_just_text(self):
# "list;" is not a verb; nothing is ever handed to a shell.
for cmd in ("list; rm -rf ~", "bash -i", "$(id)", "list 'unterminated"):
with self.assertRaises(sc.UserError, msg=cmd):
sc.parse_remote(cmd)
def test_injection_in_arguments_fails_validation(self):
argv = sc.parse_remote("status '$(id)'")
with self.assertRaises(sc.UserError):
sc.validate_name(argv[1])
class Validation(unittest.TestCase):
def test_names(self):
for ok in ("a", "fix-login", "x" * 32, "9lives"):
sc.validate_name(ok)
for bad in ("", "-x", "X", "a_b", "a/b", "..", "x" * 33, "a b", "--force"):
with self.assertRaises(sc.UserError, msg=bad):
sc.validate_name(bad)
def test_branches(self):
for ok in ("main", "feature/x-1", "v1.2"):
sc.validate_branch(ok)
for bad in ("-b", "--upload-pack=x", "a..b", "x.lock", "a/", "a b", "~x"):
with self.assertRaises(sc.UserError, msg=bad):
sc.validate_branch(bad)
def test_arity(self):
with self.assertRaises(sc.UserError):
sc.cmd_repos({"repos": {}}, ["extra"])
class AuthorizedKeys(unittest.TestCase):
def test_line_shape(self):
line = sc.authorized_line(KEY, ["37.205.10.63"], "/home/agent/.local/bin/sessions-ctl")
self.assertEqual(
line,
'from="37.205.10.63",restrict,command="/home/agent/.local/bin/sessions-ctl --remote" '
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPAP6gemgKZVguFi6Diif+dBbMAZQupimeV9OQuUotlw sessions-manager",
)
def test_rejects_bad_key_and_ip(self):
with self.assertRaises(sc.UserError):
sc.authorized_line('ssh-ed25519 AAAA" ,command="sh', ["1.2.3.4"], "/x")
with self.assertRaises(sc.UserError):
sc.authorized_line(KEY, ['1.2.3.4",command="sh'], "/x")
def test_replace_keeps_other_lines(self):
other = "ssh-ed25519 AAAAother admin@laptop"
first = sc.replace_marked_line(other + "\n", "L1 sessions-manager")
self.assertEqual(first, other + "\nL1 sessions-manager\n")
second = sc.replace_marked_line(first, "L2 sessions-manager")
self.assertEqual(second, other + "\nL2 sessions-manager\n")
self.assertEqual(sc.replace_marked_line(second, "L2 sessions-manager"), second) # idempotent
class Trust(unittest.TestCase):
def test_trust_and_untrust_preserve_other_keys(self):
with tempfile.TemporaryDirectory() as d:
cj = Path(d) / ".claude.json"
cj.write_text(json.dumps({"oauthAccount": {"x": 1}, "projects": {"/a": {"hasTrustDialogAccepted": True}}}))
cj.chmod(0o600)
sc.trust_workspace(Path("/w/s1"), cj)
data = json.loads(cj.read_text())
self.assertTrue(data["projects"]["/w/s1"]["hasTrustDialogAccepted"])
self.assertEqual(data["oauthAccount"], {"x": 1})
self.assertEqual(cj.stat().st_mode & 0o777, 0o600)
sc.untrust_workspace(Path("/w/s1"), cj)
self.assertEqual(json.loads(cj.read_text())["projects"], {"/a": {"hasTrustDialogAccepted": True}})
class ClaudeArgs(unittest.TestCase):
def test_new_then_resume(self):
state = {"name": "s1", "uuid": "11111111-2222-3333-4444-555555555555"}
with tempfile.TemporaryDirectory() as d:
projects = Path(d)
first = sc.claude_args(state, "dev-box", projects)
self.assertEqual(first[-2:], ["--session-id", state["uuid"]])
self.assertIn("dev-box-s1", first)
(projects / "-home-agent-sessions-s1").mkdir()
(projects / "-home-agent-sessions-s1" / f"{state['uuid']}.jsonl").write_text("")
self.assertEqual(sc.claude_args(state, "dev-box", projects)[-2:], ["--resume", state["uuid"]])
class MainContract(unittest.TestCase):
def test_remote_without_command_prints_json_error(self):
import contextlib, io, os
buf = io.StringIO()
os.environ.pop("SSH_ORIGINAL_COMMAND", None)
with contextlib.redirect_stdout(buf):
rc = sc.main(["--remote"])
self.assertEqual(rc, 1)
self.assertFalse(json.loads(buf.getvalue())["ok"])
if __name__ == "__main__":
unittest.main()