sessions/dev/sessions_ctl.py
agent 1b3172bd50 Add repos from the page, answer actions in place, Expo-style redesign
Add repository:
- New remote verb `add-repo KEY OWNER/NAME`. Off unless config.toml has
  [repo_add] (base_url + owners). Only listed owners; the dev box builds
  the URL itself, checks it with `git ls-remote` (bot access), then
  appends to [repos] under the lock. No URL crosses the SSH link.
- `repos` also reports where adding is allowed, so the page shows the
  form only when it's on and rejects other hosts before calling SSH.
- set_toml_string inserts after the section's last key, not after
  trailing blank lines / the next section's comments.

Responsiveness:
- web/static/app.js (progressive enhancement; every form still works
  without JS): forms go via fetch and get a JSON answer instead of
  POST-redirect-GET; buttons/cards show the change immediately; the
  list refreshes itself (15 s, 3 s while something is starting).
- `repos` is cached for 5 min (refreshed on add-repo), so a page view
  is one SSH call instead of two.
- `list` reads all unit states with one `systemctl show` instead of one
  per session: 676 -> 374 ms on the dev box with 21 sessions.
- Static assets are content-hashed and cached immutably.

Design: slate greys, hairline borders, black primary action, tinted
status badges, monospace repo/branch, two columns on desktop, stacked
on phones, light and dark.

Docs: README security model, AGENTS.md (JS convention, add-repo
invariant), config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou
2026-11-10 22:17:37 +00:00

740 lines
29 KiB
Python
Executable file

#!/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 one JSON object on stdout (except `keygen`, which prints an env
block to copy). Exit codes: 0 ok, 1 error, 2 usage.
Standard library only, so it runs with the system python3.
"""
from __future__ import annotations
import base64
import datetime as dt
import getpass
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"
HOST_KEY_PATH = os.environ.get("SESSIONS_HOST_KEY", "/etc/ssh/ssh_host_ed25519_key.pub")
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"
# One-time warning for --dangerously-skip-permissions; skipped when ~/.claude/settings.json
# has "skipDangerousModePermissionPrompt": true.
BYPASS_PROMPT = "running in Bypass Permissions mode"
# Forgejo owner (user/org) and repository names, for `add-repo`.
OWNER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$")
REPO_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$")
REMOTE_VERBS = {"list", "repos", "add-repo", "status", "create", "start", "stop", "archive", "unarchive", "health"}
DEFAULTS = {
"workspace_root": "~/sessions",
"max_running": 2,
"remote_control_prefix": socket.gethostname(),
"repos": {},
"repo_add": {},
"ssh_access": {},
}
class UserError(Exception):
"""A problem the caller can fix (bad name, unknown repo, limit reached…)."""
# ---------------------------------------------------------------- config/state
def load_config(path: Path | None = None) -> dict:
path = path or CONFIG_PATH # looked up at call time, so tests can repoint it
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.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.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.fullmatch(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_states(names: list[str]) -> dict[str, dict]:
"""State of several session units from one `systemctl show` call.
One call per unit costs ~25 ms each, which made `list` slow with a few
dozen sessions. systemctl prints one blank-line-separated block per unit;
blocks are matched back by their Id, not by position.
"""
out = {n: _unit_props({}) for n in names}
if not names:
return out
r = systemctl("show", *(UNIT.format(n) for n in names),
"-p", "Id", "-p", "ActiveState", "-p", "SubState", "-p", "UnitFileState", "-p", "NRestarts",
check=False)
by_unit = {UNIT.format(n): n for n in names}
for block in r.stdout.split("\n\n"):
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
if props.get("Id") in by_unit:
out[by_unit[props["Id"]]] = _unit_props(props)
return out
def _unit_props(props: dict) -> dict:
return {
"active": props.get("ActiveState", "unknown"),
"sub": props.get("SubState", "unknown"),
"enabled": props.get("UnitFileState") == "enabled",
"restarts": int(props.get("NRestarts") or 0),
}
def unit_state(name: str) -> dict:
return unit_states([name])[name]
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.
Sessions run with --dangerously-skip-permissions: no tool call waits for
approval. See README "Security model" for why that is acceptable here.
"""
rc_name = f"{prefix}-{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"]]
# ---------------------------------------------------------------- verbs
def session_view(state: dict, with_pane: bool = True, u: dict | None = None) -> dict:
u = u or 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"],
"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"):
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:
view["needs_attention"] = "stuck on the bypass-permissions warning; attach with tmux to accept"
return view
def cmd_list(cfg: dict, args: list[str]) -> dict:
_arity(args, 0, 0)
states = all_states()
units = unit_states([s["name"] for s in states])
return {"sessions": [session_view(s, u=units[s["name"]]) for s in states], "max_running": cfg["max_running"]}
def cmd_repos(cfg: dict, args: list[str]) -> dict:
"""The allowlist keys, plus where `add-repo` may add from (absent when it's off)."""
_arity(args, 0, 0)
out = {"repos": sorted(cfg["repos"])}
add = repo_add_settings(cfg)
if add:
out["add"] = add
return out
def repo_add_settings(cfg: dict) -> dict | None:
"""[repo_add] from the config, or None if adding repos remotely is off.
Off unless both base_url and at least one owner are set: the default is
that only the admin, editing config.toml, extends the allowlist.
"""
ra = cfg.get("repo_add") or {}
base, owners = ra.get("base_url"), ra.get("owners")
if not base or not owners:
return None
if not isinstance(base, str) or not re.fullmatch(r"(ssh|https)://[A-Za-z0-9@.:-]+/", base):
raise UserError('config: repo_add.base_url must look like "ssh://git@host:port/"')
if not isinstance(owners, list) or not all(isinstance(o, str) and OWNER_RE.fullmatch(o) for o in owners):
raise UserError("config: repo_add.owners must be a list of Forgejo user/org names")
return {"base_url": base, "owners": sorted(owners)}
def cmd_add_repo(cfg: dict, args: list[str]) -> dict:
"""add-repo KEY OWNER/REPO — add <base_url>OWNER/REPO.git to the allowlist.
The URL is built here from config; only the owner/repo path crosses the
SSH link, and only owners listed in [repo_add] are accepted. The repo must
be reachable with this box's git credentials (the bot account), which is
checked before anything is written.
"""
key, path = _arity(args, 2, 2)
add = repo_add_settings(cfg)
if not add:
raise UserError("adding repos from the web is turned off ([repo_add] in config.toml)")
validate_name(key)
owner, _, repo = path.partition("/")
repo = repo.removesuffix(".git")
if not OWNER_RE.fullmatch(owner) or not REPO_RE.fullmatch(repo) or ".." in repo:
raise UserError("repository must be OWNER/NAME")
if owner not in add["owners"]:
raise UserError(f"owner {owner!r} is not allowed; allowed: {', '.join(add['owners'])}")
url = f"{add['base_url']}{owner}/{repo}.git"
if key in cfg["repos"]:
raise UserError(f"a repo named {key!r} already exists")
dupe = [k for k, u in cfg["repos"].items() if u.lower() == url.lower()]
if dupe:
raise UserError(f"already in the allowlist as {dupe[0]!r}")
env = {**os.environ, "GIT_TERMINAL_PROMPT": "0"}
try:
r = subprocess.run(["git", "ls-remote", "--", url, "HEAD"], capture_output=True, text=True,
timeout=30, env=env)
except subprocess.TimeoutExpired:
raise UserError("the git host did not answer in time")
if r.returncode != 0:
raise UserError(f"can't reach {owner}/{repo}: check the name, and that the bot account has access")
with lock(): # re-read: another add may have landed since load_config
text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else ""
if key in load_config()["repos"]:
raise UserError(f"a repo named {key!r} already exists")
atomic_write(CONFIG_PATH, set_toml_string(text, "repos", key, url), 0o600)
return {"repo": key, "repos": sorted(load_config()["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:
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
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,
"title": title,
"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)
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))
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_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 = {}
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}
def cmd_keygen(cfg: dict, args: list[str]) -> dict:
"""Local only. Make the key prod uses and print its env block once.
The pair is generated in RAM (XDG_RUNTIME_DIR). The public half goes into
config.toml and authorized_keys; the private half is printed as one base64
line for the container's environment and then deleted, so it exists only
where you paste it.
"""
if [a for a in args if a != "--rotate"]:
raise UserError("usage: sessions-ctl keygen [--rotate]")
if cfg["ssh_access"].get("public_key", "").startswith("ssh-") and "--rotate" not in args:
raise UserError("a key is already configured; `keygen --rotate` replaces it "
"(prod stops working until its environment is updated)")
if not cfg["ssh_access"].get("allow_from_host"):
raise UserError("config: set ssh_access.allow_from_host first")
tmp = Path(tempfile.mkdtemp(dir=_user_env()["XDG_RUNTIME_DIR"], prefix="sessions-keygen-"))
try:
_run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "sessions-web", "-f", str(tmp / "id")])
public = (tmp / "id.pub").read_text().strip()
private_b64 = base64.b64encode((tmp / "id").read_bytes()).decode()
finally:
shutil.rmtree(tmp, ignore_errors=True)
text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else ""
atomic_write(CONFIG_PATH, set_toml_string(text, "ssh_access", "public_key", public), 0o600)
access = cmd_refresh_access(load_config(), [])
host_key = " ".join(Path(HOST_KEY_PATH).read_text().split()[:2])
env_block = "\n".join([
f"SESSIONS_DEV_HOST={cfg['ssh_access'].get('advertise_host') or public_address()}",
f"SESSIONS_DEV_PORT={cfg['ssh_access'].get('port', 14922)}",
f"SESSIONS_DEV_USER={getpass.getuser()}",
f"SESSIONS_DEV_HOST_KEY={host_key}",
f"SESSIONS_SSH_KEY_B64={private_b64}",
])
note = ("Paste these lines into the sessions app's environment on prod (panel -> app -> Environment).\n"
"The private key exists nowhere else now. Clear this screen afterwards (`clear`, and your\n"
"terminal's scrollback). The key only works from: " + ", ".join(access["from"]))
return {"text": env_block, "note": note, "from": access["from"]}
def set_toml_string(text: str, section: str, key: str, value: str) -> str:
"""Set `key = "value"` inside [section] of a simple TOML file, keeping the rest.
An existing key is replaced in place. A new key goes right after the
section's last key line, so blank lines and the next section's leading
comments stay where they were.
"""
if '"' in value or "\\" in value or "\n" in value:
raise UserError("refusing to write an unusual value into config.toml")
new = f'{key} = "{value}"'
out, in_section, insert_at = [], False, None
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("["):
in_section = stripped == f"[{section}]"
if in_section:
insert_at = len(out) + 1
elif in_section and re.match(rf"^{re.escape(key)}\s*=", stripped):
out.append(new)
return "\n".join(out + text.splitlines()[len(out):]) + "\n"
elif in_section and stripped and not stripped.startswith("#"):
insert_at = len(out) + 1
out.append(line)
if insert_at is None:
out += ["", f"[{section}]", new] if out else [f"[{section}]", new]
else:
out.insert(insert_at, new)
return "\n".join(out) + "\n"
def public_address() -> str:
"""The source address this box uses to reach the internet (no packet is sent)."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(("192.0.2.1", 9)) # TEST-NET-1; UDP connect only picks a route
return s.getsockname()[0]
# ---------------------------------------------------------------- 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,
"add-repo": cmd_add_repo,
"status": cmd_status,
"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,
"keygen": cmd_keygen,
"_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:])
if "text" in result and not remote:
print(result["text"]) # keygen: KEY=VALUE lines only, safe to paste as-is
if result.get("note"):
print(result["note"], file=sys.stderr)
else:
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:]))