From 1b3172bd50e452c2ec41d3da8b6acd9cc6e9790d Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 10 Nov 2026 22:17:37 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou --- AGENTS.md | 11 +- README.md | 33 ++++- dev/config.example.toml | 8 ++ dev/sessions_ctl.py | 145 ++++++++++++++++--- dev/tests/test_sessions_ctl.py | 114 +++++++++++++++ web/Containerfile | 1 + web/app.py | 248 ++++++++++++++++++++++++-------- web/static/app.css | 254 +++++++++++++++++++++++++++++++++ web/static/app.js | 224 +++++++++++++++++++++++++++++ web/tests/test_app.py | 138 +++++++++++++++++- 10 files changed, 1084 insertions(+), 92 deletions(-) create mode 100644 web/static/app.css create mode 100644 web/static/app.js diff --git a/AGENTS.md b/AGENTS.md index 79190ec..6d80f7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,12 @@ model" before changing anything that touches the SSH boundary. ## Stack and conventions - Python ≥ 3.11, **standard library only** on both sides. No pip install, so there's no supply chain to audit. Keep it that way unless there's a strong reason. -- The web page has **no JavaScript**. Plain forms, POST, then a redirect. +- The web page works **without JavaScript**: plain forms, POST, then a + redirect. `web/static/app.js` is progressive enhancement on top (fetch + + JSON answers, self-refreshing list). Keep it that way: one same-origin + script, no inline script or handlers (the CSP forbids them), no third-party + code, never insert server data as HTML except the same-origin page itself. + Static files are served with a content-hash `?v=` and cached immutably. - `sessions-ctl` prints exactly one JSON object (except `keygen`: KEY=VALUE lines on stdout, human note on stderr); exit 0/1/2. - The web app has no login: Authelia (Caddy forward_auth) in front of it is @@ -34,7 +39,9 @@ model" before changing anything that touches the SSH boundary. 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`. + of `REMOTE_VERBS`. `add-repo` is remote but stays off unless `[repo_add]` + is configured, takes `OWNER/NAME` (never a URL), accepts only listed + owners, and checks the repo with `git ls-remote` before writing config. 6. The private key is never written to disk on the dev box outside a temp dir in `XDG_RUNTIME_DIR` (RAM), which `keygen` removes. 3. `refresh-access` never writes an empty `from=`, and never touches lines diff --git a/README.md b/README.md index bcc3e5e..c6b4e8a 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ you then talk to it from the Claude app or the "Open in Claude" link. |---|---|---| | [`dev/sessions_ctl.py`](dev/sessions_ctl.py) | dev box, `~/.local/bin/sessions-ctl` | CLI + SSH forced command. Stdlib Python ≥ 3.11 | | [`dev/systemd/`](dev/systemd) | dev box, `~/.config/systemd/user/` | one unit per session; hourly key-IP refresh | -| [`web/app.py`](web/app.py) | prod, container | session list + buttons; stdlib, no JS, no login of its own | +| [`web/app.py`](web/app.py), [`web/static/`](web/static) | prod, container | session list + buttons; stdlib, optional JS, no login of its own | | [`compose.yaml`](compose.yaml) | prod, panel | how the panel builds and runs the container | ## Security model @@ -31,9 +31,10 @@ from="",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 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. + `list repos add-repo 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 crosses the link. + `add-repo KEY OWNER/NAME` (see below) sends an owner/name path, never a URL. - **`restrict`**: no PTY, no port/agent/X11 forwarding. (Tested: `-L` is refused.) - **`from=`**: the key only works from the address `reudy.net` resolves to. sshd runs with `UseDNS no`, so a hostname there would never match; instead @@ -51,8 +52,13 @@ from="",restrict,command="…/sessions-ctl --remote" ssh-ed2551 users. Authelia's policy for the domain should be `two_factor`. It is by default on prod. - Cross-site POSTs are refused by checking `Sec-Fetch-Site`/`Origin`, so no - CSRF secret is needed. The page has a strict CSP and no JavaScript. The dev - box host key is pinned (`StrictHostKeyChecking yes`). + CSRF secret is needed. The dev box host key is pinned (`StrictHostKeyChecking yes`). +- The page has a strict CSP: `script-src 'self'`, no inline script, no + third-party anything. `web/static/app.js` is progressive enhancement only: + every form also works with JavaScript off (POST, then redirect). With it, + forms are sent with `fetch` and answered as JSON, and the list refreshes + itself (every 15 s, every 3 s while a session is starting or stopping, and + only while the tab is visible). - The container is configured only by environment variables, including the SSH key (one base64 line). At start it writes the key to a 0600 file on its `/tmp` tmpfs. It runs rootless with a read-only root filesystem and all @@ -68,6 +74,17 @@ instructions only arrive through Remote Control (your claude.ai account). The remaining risk is prompt injection: a fetched page or a malicious repo file can steer a session into running commands without anyone confirming them. Only allowlist repos you trust, and treat the dev box as disposable. + +**Adding repos from the page** is off unless `config.toml` has a `[repo_add]` +section. With it, the page's *Add repository* form sends `add-repo KEY +OWNER/NAME`. The dev box accepts only owners listed in `repo_add.owners`, +builds the URL itself from `repo_add.base_url`, checks with `git ls-remote` +that the bot account can read the repo, and then appends it to `[repos]`. So +a hijacked prod could at most allowlist repos that (a) belong to an owner you +listed and (b) the bot account was already given access to. That is the same +set you'd trust anyway, but it does move the decision for that set from +editing `config.toml` to clicking a button. Removing a repo is still a +config edit. The one-time "Bypass Permissions mode" warning would block an unattended session. `"skipDangerousModePermissionPrompt": true` in `~/.claude/settings.json` suppresses it. Without that setting the page shows *"stuck on the @@ -189,7 +206,9 @@ sessions.reudy.net { | 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()` | | "stuck on the bypass-permissions warning" | Add `"skipDangerousModePermissionPrompt": true` to `~/.claude/settings.json`, then `tmux -L claude-NAME attach`, accept, detach | -| No "Open in Claude" link | The link is read from the pane once Remote Control is up; refresh after a few seconds | +| No "Open in Claude" link | The link is read from the pane once Remote Control is up; the page picks it up within seconds | +| *Add repository* missing | `[repo_add]` isn't set in `config.toml` (it's off by default). The page caches the repo list for 5 min | +| "can't reach OWNER/NAME" when adding | Typo, or the Forgejo bot account hasn't been added to that repo | ## Relation to `sess` diff --git a/dev/config.example.toml b/dev/config.example.toml index 6740691..83319d2 100644 --- a/dev/config.example.toml +++ b/dev/config.example.toml @@ -17,6 +17,14 @@ remote_control_prefix = "dev-box" [repos] sessions = "ssh://git@git.reudy.net:14922/reudy-net/sessions.git" +# Optional: let the web page add repos to [repos] ("Add repository"). +# Off while this section is absent. Only repos of the owners listed here can +# be added, the URL is always /.git, and the bot +# account must already be able to read the repo. Removing one is a manual edit. +# [repo_add] +# base_url = "ssh://git@git.reudy.net:14922/" +# owners = ["reudy-net"] + [ssh_access] # prod's key may only connect from the address(es) this name resolves to. # Re-resolved hourly by sessions-access-refresh.timer. diff --git a/dev/sessions_ctl.py b/dev/sessions_ctl.py index 69c7e0b..9fede60 100755 --- a/dev/sessions_ctl.py +++ b/dev/sessions_ctl.py @@ -66,13 +66,18 @@ 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", "archive", "unarchive", "health"} +# 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": {}, } @@ -178,9 +183,28 @@ def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess: 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) +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"), @@ -189,6 +213,10 @@ def unit_state(name: str) -> dict: } +def unit_state(name: str) -> dict: + return unit_states([name])[name] + + def tmux_socket(name: str) -> str: return f"claude-{name}" @@ -251,8 +279,8 @@ def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS) # ---------------------------------------------------------------- verbs -def session_view(state: dict, with_pane: bool = True) -> dict: - u = unit_state(state["name"]) +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"], @@ -284,12 +312,79 @@ def session_view(state: dict, with_pane: bool = True) -> dict: 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"]} + 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) - return {"repos": sorted(cfg["repos"])} + 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 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: @@ -498,27 +593,32 @@ def cmd_keygen(cfg: dict, args: list[str]) -> dict: 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.""" + """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") - lines, out, in_section, done = text.splitlines(), [], False, False - for line in lines: + new = f'{key} = "{value}"' + out, in_section, insert_at = [], False, None + for line in text.splitlines(): stripped = line.strip() if stripped.startswith("["): - if in_section and not done: - out.append(f'{key} = "{value}"') - done = True 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): - if not done: - out.append(f'{key} = "{value}"') - done = True - continue + 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 not done: - if not in_section: - out += ["", f"[{section}]"] - out.append(f'{key} = "{value}"') + 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" @@ -572,6 +672,7 @@ def _run(cmd: list[str], timeout: int = 60) -> subprocess.CompletedProcess: VERBS = { "list": cmd_list, "repos": cmd_repos, + "add-repo": cmd_add_repo, "status": cmd_status, "create": cmd_create, "start": cmd_start, diff --git a/dev/tests/test_sessions_ctl.py b/dev/tests/test_sessions_ctl.py index b9d50ac..82ccefe 100644 --- a/dev/tests/test_sessions_ctl.py +++ b/dev/tests/test_sessions_ctl.py @@ -243,6 +243,120 @@ class TomlEdit(unittest.TestCase): sc.set_toml_string("", "s", "k", 'a" \nx = "y') + def test_new_key_goes_after_last_key_not_into_next_sections_comments(self): + text = '[repos]\na = "x"\n\n# about ssh\n[ssh_access]\nk = "v"\n' + out = sc.set_toml_string(text, "repos", "b", "y") + self.assertEqual(out, '[repos]\na = "x"\nb = "y"\n\n# about ssh\n[ssh_access]\nk = "v"\n') + self.assertEqual(sc.set_toml_string("[repos]\n# none yet\n", "repos", "b", "y"), '[repos]\nb = "y"\n# none yet\n') + + +class UnitStates(unittest.TestCase): + def test_one_call_matched_by_id(self): + from unittest import mock + out = ("Id=claude-session@b.service\nActiveState=active\nSubState=running\nUnitFileState=enabled\nNRestarts=2\n\n" + "Id=claude-session@a.service\nActiveState=inactive\nSubState=dead\nUnitFileState=disabled\nNRestarts=0\n") + calls = [] + + def systemctl(*args, check=True): + calls.append(args) + return mock.Mock(stdout=out) + + with mock.patch.object(sc, "systemctl", systemctl): + states = sc.unit_states(["a", "b", "c"]) + self.assertEqual(len(calls), 1) + self.assertEqual(states["a"]["active"], "inactive") + self.assertEqual(states["b"], {"active": "active", "sub": "running", "enabled": True, "restarts": 2}) + self.assertEqual(states["c"]["active"], "unknown") # missing block: unknown, not someone else's state + with mock.patch.object(sc, "systemctl", systemctl): + self.assertEqual(sc.unit_states([]), {}) + self.assertEqual(len(calls), 1) + + +class AddRepo(unittest.TestCase): + """add-repo with git and the config file in a temp dir.""" + + BASE = "ssh://git@git.example:14922/" + + def setUp(self): + from unittest import mock + d = tempfile.TemporaryDirectory() + self.addCleanup(d.cleanup) + self.cfg_path = Path(d.name) / "config.toml" + self.cfg_path.write_text( + 'max_running = 2\n\n[repos]\nold = "ssh://git@git.example:14922/team/Old.git"\n\n' + f'[repo_add]\nbase_url = "{self.BASE}"\nowners = ["team"]\n\n[ssh_access]\nallow_from_host = "x"\n') + self.cfg_path.chmod(0o600) + self.git = [] + self.git_rc = 0 + + def run(cmd, **kw): + self.git.append(cmd) + return mock.Mock(returncode=self.git_rc, stdout="", stderr="") + + for target, value in (("CONFIG_PATH", self.cfg_path), ("STATE_DIR", Path(d.name) / "state")): + p = mock.patch.object(sc, target, value) + p.start() + self.addCleanup(p.stop) + p = mock.patch.object(sc.subprocess, "run", run) + p.start() + self.addCleanup(p.stop) + + def add(self, *args): + return sc.cmd_add_repo(sc.load_config(self.cfg_path), list(args)) + + def test_adds_and_keeps_the_rest(self): + import os, stat + before = self.cfg_path.read_text() + out = self.add("elorasmus", "team/elorasmus") + self.assertEqual(out["repos"], ["elorasmus", "old"]) + self.assertEqual(self.git, [["git", "ls-remote", "--", f"{self.BASE}team/elorasmus.git", "HEAD"]]) + after = self.cfg_path.read_text() + self.assertEqual(after, before.replace('Old.git"\n', f'Old.git"\nelorasmus = "{self.BASE}team/elorasmus.git"\n')) + self.assertEqual(stat.S_IMODE(os.stat(self.cfg_path).st_mode), 0o600) + self.assertEqual(sc.cmd_repos(sc.load_config(self.cfg_path), [])["add"], + {"base_url": self.BASE, "owners": ["team"]}) + + def test_strips_dot_git(self): + self.add("x", "team/x.git") + self.assertIn(f'x = "{self.BASE}team/x.git"', self.cfg_path.read_text()) + + def test_rejects_before_touching_git_or_config(self): + before = self.cfg_path.read_text() + bad = [ + ("Bad", "team/x"), ("x", "other/x"), ("x", "team"), ("x", "team/"), ("x", "team/a/b"), + ("x", "team/../x"), ("x", "team/-x"), ("x", "team/x y"), ("x", "team/x\n"), ("x", "../team/x"), + ("old", "team/new"), # key taken + ("again", "team/old"), # URL already listed (case-insensitive) + ] + for args in bad: + with self.assertRaises(sc.UserError, msg=args): + self.add(*args) + with self.assertRaises(sc.UserError): + self.add("x") + self.assertEqual(self.git, []) + self.assertEqual(self.cfg_path.read_text(), before) + + def test_unreachable_repo_is_not_added(self): + before = self.cfg_path.read_text() + self.git_rc = 128 + with self.assertRaises(sc.UserError): + self.add("x", "team/x") + self.assertEqual(self.cfg_path.read_text(), before) + + def test_off_without_repo_add_section(self): + cfg = sc.load_config(self.cfg_path) + cfg["repo_add"] = {} + with self.assertRaises(sc.UserError): + sc.cmd_add_repo(cfg, ["x", "team/x"]) + self.assertNotIn("add", sc.cmd_repos(cfg, [])) + cfg["repo_add"] = {"base_url": "file:///tmp/", "owners": ["team"]} + with self.assertRaises(sc.UserError): + sc.cmd_add_repo(cfg, ["x", "team/x"]) + + def test_is_a_remote_verb(self): + self.assertEqual(sc.parse_remote("add-repo x team/x"), ["add-repo", "x", "team/x"]) + + class Keygen(unittest.TestCase): def test_keygen_end_to_end_in_temp_dirs(self): import base64, os diff --git a/web/Containerfile b/web/Containerfile index e91b354..29e6995 100644 --- a/web/Containerfile +++ b/web/Containerfile @@ -9,6 +9,7 @@ RUN apt-get update \ WORKDIR /app COPY app.py /app/app.py +COPY static/ /app/static/ USER 10001 ENV PYTHONUNBUFFERED=1 SESSIONS_LISTEN=0.0.0.0:8470 diff --git a/web/app.py b/web/app.py index beb7b6b..5617021 100644 --- a/web/app.py +++ b/web/app.py @@ -24,6 +24,7 @@ from __future__ import annotations import base64 import binascii +import hashlib import html import json import os @@ -33,7 +34,10 @@ import signal import subprocess import sys import tempfile +import threading +import time import urllib.parse +from concurrent.futures import ThreadPoolExecutor from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -164,100 +168,216 @@ def allowed_user(user: str, allowed: set[str]) -> bool: return bool(user) and (not allowed or user in allowed) +# ---------------------------------------------------------------- repo input + + +# What the "Add repository" box accepts: OWNER/NAME, or a clone URL of the +# git host the dev box adds from (ssh://, https:// or scp-style git@host:). +REPO_INPUT_RE = re.compile( + r"(?:(?Pssh|https?)://(?:[A-Za-z0-9._-]+@)?(?P[A-Za-z0-9.-]+)(?::\d+)?/" + r"|git@(?P[A-Za-z0-9.-]+):)?" + r"(?P[A-Za-z0-9][A-Za-z0-9._-]{0,39})/(?P[A-Za-z0-9][A-Za-z0-9._-]{0,99}?)(?:\.git)?/?" +) + + +def parse_repo_input(text: str, base_url: str) -> tuple[str, str]: + """'ssh://git@host:14922/team/App.git' -> ('team', 'App'). Raises ValueError. + + A URL must point at the same host as the dev box's base_url, because the + dev box only ever builds URLs on that host: pasting a GitHub URL must fail + loudly rather than silently add the same path from the git host. + """ + m = REPO_INPUT_RE.fullmatch(text.strip()) + if not m or ".." in m["repo"]: + raise ValueError("enter OWNER/NAME or the repo's clone URL") + host = m["host"] or m["scp_host"] + if host and host.lower() != (urllib.parse.urlsplit(base_url).hostname or "").lower(): + raise ValueError(f"only repos on {urllib.parse.urlsplit(base_url).hostname} can be added") + return m["owner"], m["repo"] + + +def key_from_repo(repo: str) -> str: + """'My_App.v2' -> 'my-app-v2': the allowlist key the page offers by default.""" + return re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")[:32].rstrip("-") + + # ---------------------------------------------------------------- HTML -CSS = """ -:root{--bg:#f6f5f2;--fg:#1d1d1b;--muted:#6b6a65;--card:#fff;--line:#e3e1db;--accent:#b4532a;--ok:#2f7d4f;--warn:#a06a00;--bad:#b3261e} -@media (prefers-color-scheme:dark){:root{--bg:#161615;--fg:#ecebe6;--muted:#9c9a93;--card:#1f1f1d;--line:#34332f;--accent:#e08a5c;--ok:#6cc08f;--warn:#e0b050;--bad:#f08a80}} -*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.45 system-ui,-apple-system,sans-serif} -main{max-width:720px;margin:0 auto;padding:20px 16px 48px} -header{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin-bottom:16px} -h1{font-size:1.3rem;margin:0}h2{font-size:1rem;margin:28px 0 10px;color:var(--muted);font-weight:600;text-transform:uppercase;letter-spacing:.04em} -.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:10px} -.row{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap} -.name{font-weight:600;font-size:1.05rem}.meta{color:var(--muted);font-size:.88rem} -.pill{font-size:.78rem;padding:2px 8px;border-radius:99px;border:1px solid currentColor} -.active{color:var(--ok)}.activating,.deactivating{color:var(--warn)}.inactive,.failed,.unknown{color:var(--bad)} -.actions{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap} -button,.btn{font:inherit;padding:8px 14px;border-radius:8px;border:1px solid var(--line);background:var(--card);color:var(--fg);cursor:pointer;text-decoration:none;display:inline-block} -.primary{background:var(--accent);border-color:var(--accent);color:#fff} -form.inline{display:inline}label{display:block;font-size:.88rem;color:var(--muted);margin:10px 0 4px} -input,select{font:inherit;width:100%;padding:9px 10px;border-radius:8px;border:1px solid var(--line);background:var(--bg);color:var(--fg)} -.flash{padding:10px 14px;border-radius:8px;margin-bottom:14px;border:1px solid}.flash.err{color:var(--bad)}.flash.ok{color:var(--ok)} -.warn{color:var(--warn);font-size:.9rem;margin-top:6px}a{color:var(--accent)} -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} -""" +STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") + + +def _static(name: str) -> bytes: + with open(os.path.join(STATIC, name), "rb") as f: + return f.read() + + +ASSETS = {"/app.css": (_static("app.css"), "text/css; charset=utf-8"), + "/app.js": (_static("app.js"), "text/javascript; charset=utf-8")} +# Asset URLs carry a content hash, so they can be cached forever and a deploy +# still takes effect on the next page load. +ASSET_VERSION = hashlib.sha256(b"".join(b for b, _ in ASSETS.values())).hexdigest()[:10] + +STATE_LABEL = {"active": "Running", "activating": "Starting", "deactivating": "Stopping", + "reloading": "Reloading", "inactive": "Stopped", "failed": "Failed"} + +MARK = ('') def page(title: str, body: str) -> bytes: return f""" -{html.escape(title)} -
{body}
""".encode() + +{html.escape(title)} + +{body}""".encode() def e(v) -> str: return html.escape(str(v if v is not None else "")) -def action(verb: str, name: str) -> str: +def action(verb: str, name: str, cls: str = "") -> str: return (f'
' - f'
') + f'' + f'') + + +def badge(state: str) -> str: + return f'{e(STATE_LABEL.get(state, state.title()))}' def session_card(s: dict, actions: str, cls: str = "") -> str: - warn = f'
⚠ {e(s["needs_attention"])}
' if s.get("needs_attention") else "" + warn = f'
{e(s["needs_attention"])}
' if s.get("needs_attention") else "" restarts = f' · restarted {e(s["restarts"])}×' if s.get("restarts") else "" - return f"""
{e(s.get("title") or s["name"])} -{e(s["state"])}
-
{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}
{warn} -
{actions}
""" + linked = " data-linked" if s.get("remote_control_url") else "" + created = e(s["created_at"]) + return f"""
+

{e(s.get("title") or s["name"])}

{badge(s["state"])}
+
{e(s["repo"])}/{e(s["branch"])}
+
Created {restarts}
{warn} +
{actions}
""" -def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes: - parts = [f'

Sessions

{e(user)}
'] - if flash: - parts.append(f'
{e(flash[1])}
') +def live_section(listing: dict) -> str: + """The part of the page that changes on its own; app.js re-fetches and swaps it.""" + parts = [] if not listing.get("ok"): - parts.append(f'
{e(listing.get("error", "dev box error"))}
') + parts.append(f'
{e(listing.get("error", "dev box error"))}
') 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'

Running {running} of {e(listing.get("max_running", "?"))}

') - if not sessions and listing.get("ok"): - parts.append('

No sessions yet.

') + parts.append(f'

Active

' + f'{running} of {e(listing.get("max_running", "?"))} running
') + cards = [] for s in sessions: link = (f'Open in Claude' if s.get("remote_control_url") and s["state"] == "active" else "") verb = "stop" if s["enabled"] else "start" - parts.append(session_card(s, link + action(verb, s["name"]) + action("archive", s["name"]))) + cards.append(session_card(s, link + action(verb, s["name"], "secondary") + + action("archive", s["name"], "ghost"))) + if not sessions and listing.get("ok"): + cards.append('
No sessions yet' + 'Create one and it shows up here and in the Claude app.
') + parts.append(f'
{"".join(cards)}
') if archived: - cards = "".join(session_card(s, action("unarchive", s["name"]), "archived") for s in archived) - parts.append(f'

Archived ({len(archived)})

{cards}
') + old = "".join(session_card(s, action("unarchive", s["name"], "secondary"), "archived") for s in archived) + parts.append(f'
Archived {len(archived)}' + f'
{old}
') + return f'
{"".join(parts)}
' + +def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes: + toast = f'
{e(flash[1])}
' if flash else "" options = "".join(f'' for r in repos.get("repos", [])) - parts.append(f"""

New session

+ add = repos.get("add") + add_form = "" + if add: + host = urllib.parse.urlsplit(add["base_url"]).hostname or "" + owners = ", ".join(e(o) for o in add["owners"]) + add_form = f"""

Add repository

+ + + + + +

Repos on {e(host)} owned by {owners}. The bot account must already have access. Sessions run with no permission prompts, so add only repos you trust.

+
""" + + body = f"""
+{MARK}Sessions{e(user)}
+
{toast}
+
+
+

Sessions

Claude Code on the dev box, with Remote Control.

+{live_section(listing)} +
+ +
""" + return page("Sessions", body) # ---------------------------------------------------------------- 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"} +DONE = {"/start": "Started", "/stop": "Stopped", "/archive": "Archived", "/unarchive": "Restored"} class App: + REPOS_TTL = 300 # the allowlist rarely changes; add-repo refreshes it at once + def __init__(self, env: dict, dev: DevBox): self.dev = dev self.auth_header = env.get("SESSIONS_AUTH_HEADER", "Remote-User") self.allowed_users = {u.strip() for u in env.get("SESSIONS_ALLOWED_USERS", "").split(",") if u.strip()} + self._repos: dict | None = None + self._repos_at = 0.0 + self._lock = threading.Lock() + + def repos(self) -> dict: + """The `repos` answer, cached so a page view costs one SSH call, not two.""" + with self._lock: + if self._repos and time.monotonic() - self._repos_at < self.REPOS_TTL: + return self._repos + r = self.dev.call("repos") + if r.get("ok"): + self.set_repos(r) + return r + + def set_repos(self, r: dict) -> None: + with self._lock: + self._repos, self._repos_at = r, time.monotonic() + + def page_data(self) -> tuple[dict, dict]: + """`list` and (on a cache miss) `repos`, side by side over the shared connection.""" + with ThreadPoolExecutor(max_workers=1) as pool: + repos = pool.submit(self.repos) + listing = self.dev.call("list") + return listing, (repos.result() if listing.get("ok") else {}) + + def add_repo(self, f: dict) -> tuple[dict, str]: + add = self.repos().get("add") + if not add: + return {"ok": False, "error": "adding repos is turned off on the dev box ([repo_add] in config.toml)"}, "" + try: + owner, repo = parse_repo_input(f.get("url", ""), add["base_url"]) + except ValueError as err: + return {"ok": False, "error": str(err)}, "" + key = f.get("key", "").strip() or key_from_repo(repo) + r = self.dev.call("add-repo", key, f"{owner}/{repo}", timeout=60) + if r.get("ok"): + self.set_repos({"ok": True, "repos": r["repos"], "add": add}) + return r, f"Added {key} — it's now in the Repository list" def make_handler(app: App): @@ -271,12 +391,15 @@ def make_handler(app: App): def log_message(self, fmt, *args): sys.stderr.write(f"{self.user() or '-'} {fmt % args}\n") - def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", headers: dict | None = None): + def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", + headers: dict | None = None, cache: str = "no-store"): self.send_response(status) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) - self.send_header("Cache-Control", "no-store") - self.send_header("Content-Security-Policy", "default-src 'none'; style-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'") + self.send_header("Cache-Control", cache) + self.send_header("Content-Security-Policy", + "default-src 'none'; style-src 'self'; script-src 'self'; connect-src 'self'; " + "form-action 'self'; frame-ancestors 'none'; base-uri 'none'") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "no-referrer") for k, v in (headers or {}).items(): @@ -312,8 +435,9 @@ def make_handler(app: App): return self.send(200, b"ok\n", "text/plain") if self.refuse_unauthenticated(): return - if path == "/app.css": - return self.send(200, CSS.encode(), "text/css") + if path in ASSETS: + body, ctype = ASSETS[path] + return self.send(200, body, ctype, cache="private, max-age=31536000, immutable") if path != "/": return self.send(404, b"not found\n", "text/plain") flash = None @@ -322,8 +446,7 @@ def make_handler(app: App): flash = ("ok", q["ok"][0][:200]) elif "err" in q: flash = ("err", q["err"][0][:300]) - listing = app.dev.call("list") - repos = app.dev.call("repos") if listing.get("ok") else {} + listing, repos = app.page_data() self.send(200, dashboard(listing, repos, self.user(), flash)) def do_POST(self): @@ -338,13 +461,22 @@ def make_handler(app: App): 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" + done = f"Created {args[0]} — it appears in the Claude app in a few seconds" + elif path == "/add-repo": + r, done = app.add_repo(f) elif path in DONE: r = app.dev.call(path[1:], 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")) + self.log_message("%s %s -> %s", path, f.get("name", "") or f.get("url", ""), + "ok" if r.get("ok") else r.get("error")) + if "application/json" in self.headers.get("Accept", ""): + # app.js: answer in place; the page updates without a reload. + out = {"ok": True, "message": done} if r.get("ok") else {"ok": False, "error": r.get("error", "failed")} + if r.get("ok") and "repos" in r: + out["repos"] = r["repos"] + return self.send(200, json.dumps(out).encode(), "application/json") key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed")) self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + urllib.parse.urlencode({key: msg})}) diff --git a/web/static/app.css b/web/static/app.css new file mode 100644 index 0000000..36e9efb --- /dev/null +++ b/web/static/app.css @@ -0,0 +1,254 @@ +/* sessions-web. A quiet, monochrome UI in the style of Expo's design language: + slate greys, hairline borders, a black primary action, soft tinted status badges. */ + +:root { + --bg: #ffffff; + --bg-subtle: #f8f9fa; + --bg-hover: #f1f3f5; + --line: #e6e8eb; + --line-strong: #d7dbdf; + --fg: #11181c; + --fg-2: #687076; + --fg-3: #889096; + --primary: #11181c; + --on-primary: #ffffff; + --ok: #18794e; --ok-bg: #e9f9ee; + --warn: #ad5700; --warn-bg: #fff4d5; + --bad: #cd2b31; --bad-bg: #ffefef; + --idle: #687076; --idle-bg: #f1f3f5; + --focus: #0091ff; + --shadow: 0 1px 2px rgba(17, 24, 28, .04), 0 1px 1px rgba(17, 24, 28, .03); + --shadow-lg: 0 10px 30px -10px rgba(17, 24, 28, .25); + --radius: 12px; + --radius-sm: 8px; + --font: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; + --mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + color-scheme: light; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #151718; + --bg-subtle: #1a1d1e; + --bg-hover: #202425; + --line: #2b2f31; + --line-strong: #393e40; + --fg: #ecedee; + --fg-2: #9ba1a6; + --fg-3: #787f85; + --primary: #ecedee; + --on-primary: #151718; + --ok: #4cc38a; --ok-bg: #0f291e; + --warn: #f1a10d; --warn-bg: #2c2100; + --bad: #ff6369; --bad-bg: #3c181a; + --idle: #9ba1a6; --idle-bg: #202425; + --focus: #52a9ff; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); + --shadow-lg: 0 10px 30px -10px rgba(0, 0, 0, .7); + color-scheme: dark; + } +} + +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html { -webkit-text-size-adjust: 100%; } +body { + margin: 0; + background: var(--bg); + color: var(--fg); + font: 15px/1.5 var(--font); + -webkit-font-smoothing: antialiased; + font-feature-settings: "cv11", "ss01"; +} +a { color: inherit; } +h1, h2, h3 { margin: 0; letter-spacing: -0.015em; } +:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } + +.wrap { max-width: 1080px; margin: 0 auto; padding: 0 16px; } + +/* ---------------------------------------------------------------- top bar */ + +.top { + position: sticky; top: 0; z-index: 10; + background: color-mix(in srgb, var(--bg) 85%, transparent); + -webkit-backdrop-filter: saturate(180%) blur(12px); + backdrop-filter: saturate(180%) blur(12px); + border-bottom: 1px solid var(--line); +} +.top-inner { height: 56px; display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.brand { display: flex; align-items: center; gap: 10px; font-weight: 600; text-decoration: none; letter-spacing: -0.01em; } +.mark { width: 24px; height: 24px; flex: none; } +.mark rect { fill: var(--primary); } +.mark path { stroke: var(--on-primary); } +.user { + font-size: 13px; color: var(--fg-2); + padding: 4px 10px; border: 1px solid var(--line); border-radius: 99px; + max-width: 50vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; +} + +/* ---------------------------------------------------------------- layout */ + +.grid { display: grid; gap: 32px; padding-top: 32px; padding-bottom: 64px; } +@media (min-width: 900px) { + .grid { grid-template-columns: minmax(0, 1fr) 340px; gap: 48px; padding-top: 48px; } + .col-side { position: sticky; top: 88px; align-self: start; } +} + +.intro h1 { font-size: 30px; font-weight: 700; letter-spacing: -0.025em; line-height: 1.2; } +.intro p { margin: 6px 0 0; color: var(--fg-2); } + +.section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin: 32px 0 12px; } +.section-head h2 { font-size: 17px; font-weight: 600; } +.counter { font-size: 13px; color: var(--fg-2); font-variant-numeric: tabular-nums; } + +.list { display: grid; gap: 12px; } + +/* ---------------------------------------------------------------- cards */ + +.card { + background: var(--bg); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; + box-shadow: var(--shadow); + transition: border-color .15s, opacity .2s, transform .2s; +} +.card:hover { border-color: var(--line-strong); } +.card-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } +.title { font-size: 16px; font-weight: 600; line-height: 1.35; overflow-wrap: anywhere; } +.meta { margin-top: 4px; font-size: 13px; color: var(--fg-2); display: flex; flex-wrap: wrap; gap: 0 6px; } +.mono { font-family: var(--mono); font-size: 12.5px; overflow-wrap: anywhere; } +.dim { color: var(--fg-3); } +.warn { + margin-top: 12px; padding: 8px 12px; border-radius: var(--radius-sm); + background: var(--warn-bg); color: var(--warn); font-size: 13px; +} +.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } +.card.archived { background: var(--bg-subtle); box-shadow: none; } +.card.archived .title { color: var(--fg-2); } +.card.pending { opacity: .7; } +.card.leaving { opacity: 0; transform: scale(.98); } +.card.ghost { border-style: dashed; box-shadow: none; } +.card.ghost .title { color: var(--fg-2); } + +.empty { + display: grid; gap: 4px; text-align: center; padding: 40px 16px; + border: 1px dashed var(--line-strong); border-radius: var(--radius); color: var(--fg-2); font-size: 14px; +} +.empty strong { color: var(--fg); font-weight: 600; } + +/* ---------------------------------------------------------------- badges */ + +.badge { + flex: none; display: inline-flex; align-items: center; gap: 6px; + font-size: 12px; font-weight: 500; line-height: 1; + padding: 5px 9px; border-radius: 99px; + background: var(--idle-bg); color: var(--idle); +} +.badge i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; } +.badge.active { background: var(--ok-bg); color: var(--ok); } +.badge.activating, .badge.deactivating, .badge.reloading { background: var(--warn-bg); color: var(--warn); } +.badge.activating i, .badge.deactivating i, .badge.reloading i { animation: pulse 1s ease-in-out infinite; } +.badge.failed, .badge.unknown { background: var(--bad-bg); color: var(--bad); } + +/* ---------------------------------------------------------------- buttons */ + +.btn { + font: inherit; font-size: 14px; font-weight: 500; line-height: 20px; + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + min-height: 36px; padding: 7px 14px; + border-radius: var(--radius-sm); border: 1px solid transparent; + background: var(--primary); color: var(--on-primary); + text-decoration: none; cursor: pointer; white-space: nowrap; + transition: background-color .15s, border-color .15s, opacity .15s; +} +.btn:hover { opacity: .88; } +.btn.secondary { background: var(--bg); color: var(--fg); border-color: var(--line-strong); } +.btn.secondary:hover { background: var(--bg-hover); opacity: 1; } +.btn.ghost { background: transparent; color: var(--fg-2); } +.btn.ghost:hover { background: var(--bg-hover); color: var(--fg); opacity: 1; } +.btn.wide { flex: 1; } +.btn:disabled { cursor: progress; opacity: .6; } +.btn.loading::before { + content: ""; width: 14px; height: 14px; border-radius: 50%; + border: 2px solid currentColor; border-right-color: transparent; + animation: spin .7s linear infinite; +} +form.inline { display: contents; } + +/* ---------------------------------------------------------------- panels and forms */ + +.col-side { display: grid; gap: 16px; align-content: start; } +.panel { + background: var(--bg-subtle); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 20px; +} +.panel h2 { font-size: 15px; font-weight: 600; margin-bottom: 4px; } +details.panel > summary { cursor: pointer; list-style: none; display: flex; align-items: center; justify-content: space-between; } +details.panel > summary::-webkit-details-marker { display: none; } +details.panel > summary h2 { margin: 0; } +details.panel > summary::after { content: "+"; font-size: 18px; color: var(--fg-2); line-height: 1; } +details.panel[open] > summary::after { content: "–"; } +details.panel[open] > summary { margin-bottom: 4px; } + +label { display: block; font-size: 13px; font-weight: 500; color: var(--fg); margin: 14px 0 6px; } +.opt { font-weight: 400; color: var(--fg-3); } +input, select { + font: inherit; font-size: 15px; width: 100%; + min-height: 40px; padding: 8px 12px; + border-radius: var(--radius-sm); border: 1px solid var(--line-strong); + background: var(--bg); color: var(--fg); + transition: border-color .15s, box-shadow .15s; +} +input::placeholder { color: var(--fg-3); } +input:focus, select:focus { outline: none; border-color: var(--focus); box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 25%, transparent); } +select { + appearance: none; -webkit-appearance: none; padding-right: 36px; + background-image: linear-gradient(45deg, transparent 50%, var(--fg-2) 50%), linear-gradient(135deg, var(--fg-2) 50%, transparent 50%); + background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%; + background-size: 5px 5px; background-repeat: no-repeat; +} +.panel .actions { margin-top: 20px; } +.hint { margin: 12px 0 0; font-size: 12.5px; color: var(--fg-2); } +.note { margin: 0; font-size: 12.5px; color: var(--fg-3); padding: 0 4px; } + +/* ---------------------------------------------------------------- archive */ + +details.archive { margin-top: 28px; } +details.archive > summary { + cursor: pointer; list-style: none; display: inline-flex; align-items: center; gap: 8px; + font-size: 14px; font-weight: 500; color: var(--fg-2); margin-bottom: 12px; +} +details.archive > summary::-webkit-details-marker { display: none; } +details.archive > summary::before { content: "›"; display: inline-block; transition: transform .15s; font-size: 16px; } +details.archive[open] > summary::before { transform: rotate(90deg); } +.count { font-size: 12px; padding: 1px 7px; border-radius: 99px; background: var(--bg-hover); } + +/* ---------------------------------------------------------------- messages */ + +.callout { padding: 12px 14px; border-radius: var(--radius-sm); font-size: 14px; margin-top: 24px; } +.callout.err { background: var(--bad-bg); color: var(--bad); } + +#toasts { + position: fixed; z-index: 20; left: 16px; right: 16px; bottom: 16px; + display: grid; gap: 8px; justify-items: center; pointer-events: none; +} +@media (min-width: 640px) { #toasts { left: auto; right: 24px; bottom: 24px; justify-items: end; } } +.toast { + pointer-events: auto; max-width: 420px; + padding: 12px 16px; border-radius: var(--radius-sm); + background: var(--primary); color: var(--on-primary); + font-size: 14px; box-shadow: var(--shadow-lg); + animation: rise .2s ease-out; transition: opacity .3s, transform .3s; +} +.toast.err { background: var(--bad); color: #fff; } +.toast.out { opacity: 0; transform: translateY(6px); } + +@keyframes spin { to { transform: rotate(360deg); } } +@keyframes pulse { 50% { opacity: .35; } } +@keyframes rise { from { opacity: 0; transform: translateY(8px); } } +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition: none !important; } +} diff --git a/web/static/app.js b/web/static/app.js new file mode 100644 index 0000000..95cb956 --- /dev/null +++ b/web/static/app.js @@ -0,0 +1,224 @@ +// sessions-web: progressive enhancement. The page works without this file; +// with it, buttons answer in place (no reload) and the list keeps itself fresh. +// +// - Every POST form is sent with fetch() and `Accept: application/json`; the +// server then answers {ok, message|error} instead of redirecting. +// - The button and card show the change at once; the real state follows from +// a background refresh, which re-fetches "/" and swaps #live and the +// Repository options. Nothing from the server is inserted as HTML except +// that same-origin page. +// - The list refreshes every 15 s (every 3 s while something is starting or +// stopping) and only while the tab is visible. +(() => { + "use strict"; + + const $ = (sel, root = document) => root.querySelector(sel); + const BUSY_LABEL = { + start: "Starting", stop: "Stopping", archive: "Archiving", unarchive: "Restoring", + create: "Creating", "add-repo": "Checking", + }; + const SLOW = 15000, FAST = 3000; + let inFlight = 0, timer = 0; + + // The no-JS flow lands on /?ok=… — drop it so a reload doesn't repeat it. + if (location.search) history.replaceState(null, "", location.pathname); + + // ------------------------------------------------------------ toasts + + function dismiss(el, after) { + setTimeout(() => { el.classList.add("out"); setTimeout(() => el.remove(), 300); }, after); + } + + function toast(kind, text) { + const el = document.createElement("div"); + el.className = "toast " + kind; + el.setAttribute("role", kind === "err" ? "alert" : "status"); + el.textContent = text; + $("#toasts").appendChild(el); + dismiss(el, kind === "err" ? 9000 : 4500); + } + + document.querySelectorAll("#toasts .toast").forEach((el) => dismiss(el, 6000)); + + // ------------------------------------------------------------ relative times + + function ago(iso) { + const s = (Date.now() - Date.parse(iso)) / 1000; + if (!isFinite(s)) return null; + if (s < 60) return "just now"; + const units = [["d", 86400], ["h", 3600], ["min", 60]]; + for (const [u, n] of units) if (s >= n) return `${Math.floor(s / n)} ${u} ago`; + return null; + } + + function humanizeTimes(root) { + root.querySelectorAll("time[datetime]").forEach((t) => { + const rel = ago(t.dateTime); + if (rel) { t.title = t.textContent; t.textContent = rel; } + }); + } + + // ------------------------------------------------------------ refresh + + function needsFastPoll() { + return !!$('#live [data-state="activating"], #live [data-state="deactivating"], #live .card.ghost') || + !!$('#live [data-state="active"]:not([data-linked])'); // waiting for the Remote Control link + } + + function schedule() { + clearTimeout(timer); + if (!document.hidden) timer = setTimeout(refresh, needsFastPoll() ? FAST : SLOW); + } + + async function refresh() { + if (inFlight) return schedule(); // an action's own refresh follows it + let res; + try { + res = await fetch("/", { headers: { Accept: "text/html" }, cache: "no-store", credentials: "same-origin" }); + } catch { + return schedule(); // offline, or the login expired (redirect to another origin) + } + if (!res.ok || inFlight) return schedule(); + const doc = new DOMParser().parseFromString(await res.text(), "text/html"); + const live = $("#live", doc); + if (!live) return schedule(); + swapLive(live); + swapRepos($("#repo", doc)); + schedule(); + } + + function swapLive(fresh) { + const current = $("#live"); + const wasOpen = $("details.archive", current)?.open; + const archive = $("details.archive", fresh); + if (archive && wasOpen) archive.open = true; + humanizeTimes(fresh); + current.replaceWith(document.adoptNode(fresh)); + } + + function swapRepos(freshSelect) { + const select = $("#repo"); + if (!select || !freshSelect) return; + setRepoOptions([...freshSelect.options].map((o) => o.value)); + } + + function setRepoOptions(names, pick) { + const select = $("#repo"); + const have = [...select.options].map((o) => o.value); + if (have.join("\n") === names.join("\n") && !pick) return; + const keep = pick || select.value; + select.replaceChildren(...names.map((n) => new Option(n, n))); + if (names.includes(keep)) select.value = keep; + } + + // ------------------------------------------------------------ actions + + // Show the action as happening right away. Returns an undo for failures. + function showPending(verb, form, button) { + const undo = []; + const label = button.textContent; + button.disabled = true; + button.classList.add("loading"); + button.textContent = BUSY_LABEL[verb] || "Working"; + undo.push(() => { button.disabled = false; button.classList.remove("loading"); button.textContent = label; }); + + const card = form.closest(".card"); + if (card) { + card.classList.add("pending"); + card.querySelectorAll("button").forEach((b) => { b.disabled = true; }); + const badge = $(".badge", card); + const old = badge.cloneNode(true); + const state = { start: "activating", stop: "deactivating", archive: "deactivating" }[verb]; + if (state) { + badge.className = "badge " + state; + badge.lastChild.textContent = BUSY_LABEL[verb]; + card.dataset.state = state; + } + if (verb === "archive" || verb === "unarchive") card.classList.add("leaving"); + undo.push(() => { card.classList.remove("pending", "leaving"); badge.replaceWith(old); }); + } + + if (verb === "create") { + const ghost = document.createElement("article"); + ghost.className = "card ghost"; + ghost.innerHTML = '

' + + 'Cloning
'; + $(".title", ghost).textContent = new FormData(form).get("name"); + $(".mono", ghost).textContent = new FormData(form).get("repo"); + const list = $("#live .list"); + const empty = $(".empty", list); + if (empty) empty.hidden = true; + list.prepend(ghost); + undo.push(() => { ghost.remove(); if (empty) empty.hidden = false; }); + } + return () => undo.forEach((f) => f()); + } + + async function submit(form, button) { + const verb = new URL(form.action).pathname.slice(1); + const body = new URLSearchParams(new FormData(form)); + const undo = showPending(verb, form, button); + inFlight++; + clearTimeout(timer); + let data; + try { + const res = await fetch(form.action, { + method: "POST", body, credentials: "same-origin", headers: { Accept: "application/json" }, + }); + data = res.headers.get("Content-Type")?.startsWith("application/json") + ? await res.json() + : { ok: false, error: `${res.status} ${(await res.text()).trim().slice(0, 200)}` }; + } catch { + data = { ok: false, error: "Couldn't reach the server. Check your connection and try again." }; + } + inFlight--; + + if (data.ok) { + toast("ok", data.message); + if (!form.closest(".card")) undo(); // side panel forms stay; cards are replaced by the refresh + if (verb === "create") { + const repo = form.elements.repo.value; + form.reset(); + form.elements.repo.value = repo; + } + if (verb === "add-repo") { + const added = new FormData(form).get("key") || null; + form.reset(); + if (data.repos) setRepoOptions(data.repos, data.repos.find((r) => r === added) || newest(data.repos)); + $("#name")?.focus(); + } + } else { + undo(); + toast("err", data.error || "Something went wrong"); + } + refresh(); + } + + // The key add-repo just added: the one that wasn't in the list before. + function newest(names) { + const before = new Set([...$("#repo").options].map((o) => o.value)); + return names.find((n) => !before.has(n)); + } + + document.addEventListener("submit", (ev) => { + const form = ev.target; + if (!(form instanceof HTMLFormElement) || form.method.toLowerCase() !== "post") return; + ev.preventDefault(); + const button = ev.submitter || $("button", form); + if (button?.disabled) return; + submit(form, button); + }); + + document.addEventListener("click", (ev) => { + const link = ev.target.closest("[data-refresh]"); + if (!link) return; + ev.preventDefault(); + link.classList.add("loading"); + refresh().finally(() => link.classList.remove("loading")); + }); + + document.addEventListener("visibilitychange", () => (document.hidden ? clearTimeout(timer) : refresh())); + + humanizeTimes(document); + schedule(); +})(); diff --git a/web/tests/test_app.py b/web/tests/test_app.py index 049cd53..35598d7 100644 --- a/web/tests/test_app.py +++ b/web/tests/test_app.py @@ -90,15 +90,15 @@ class Rendering(unittest.TestCase): "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("
") + live, archived = out.split('
') self.assertIn("LIVE", live) self.assertIn('action="/archive"', live) self.assertNotIn("OLD", live) - self.assertIn("Archived (1)", archived) + 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"
", no_archive) + self.assertNotIn(b'
', no_archive) def test_escapes_everything(self): listing = {"ok": True, "max_running": 2, "sessions": [{ @@ -112,5 +112,137 @@ class Rendering(unittest.TestCase): self.assertIn("<b>", out) + def test_add_repo_form_only_when_the_dev_box_allows_it(self): + listing = {"ok": True, "max_running": 2, "sessions": []} + self.assertNotIn(b'action="/add-repo"', app.dashboard(listing, {"repos": ["a"]}, "u", None)) + on = app.dashboard(listing, {"repos": ["a"], "add": {"base_url": "ssh://git@git.example:14922/", + "owners": ["team"]}}, "u", None).decode() + self.assertIn('action="/add-repo"', on) + self.assertIn("git.example", on) + + def test_assets_are_versioned_and_page_has_no_inline_script(self): + out = app.dashboard({"ok": True, "sessions": []}, {}, "u", None).decode() + self.assertIn(f'src="/app.js?v={app.ASSET_VERSION}"', out) + self.assertNotRegex(out, r"]*\bsrc=)") # CSP has no 'unsafe-inline' + + +class RepoInput(unittest.TestCase): + BASE = "ssh://git@git.reudy.net:14922/" + + def test_accepts_paths_and_urls_on_the_git_host(self): + for text in ("reudy-net/elorasmus", "reudy-net/elorasmus.git", " reudy-net/elorasmus/ ", + "ssh://git@git.reudy.net:14922/reudy-net/elorasmus.git", + "https://git.reudy.net/reudy-net/elorasmus", "https://GIT.reudy.net/reudy-net/elorasmus.git", + "git@git.reudy.net:reudy-net/elorasmus.git"): + self.assertEqual(app.parse_repo_input(text, self.BASE), ("reudy-net", "elorasmus"), text) + + def test_rejects_other_hosts_and_odd_paths(self): + for text in ("https://github.com/reudy-net/elorasmus", "git@github.com:reudy-net/x.git", + "elorasmus", "a/b/c", "reudy-net/../x", "reudy-net/x y", "reudy-net/x;id", "", + "file:///etc/passwd", "reudy-net/-x", "reudy-net/x\ny"): + with self.assertRaises(ValueError, msg=text): + app.parse_repo_input(text, self.BASE) + + def test_key_from_repo(self): + self.assertEqual(app.key_from_repo("Papure"), "papure") + self.assertEqual(app.key_from_repo("My_App.v2"), "my-app-v2") + self.assertEqual(app.key_from_repo("x" * 40), "x" * 32) + + +class Server(unittest.TestCase): + """The real handler on a loopback port, with the dev box faked.""" + + class FakeDev: + def __init__(self): + self.calls = [] + + def call(self, *args, timeout=60): + self.calls.append(args) + if args[0] == "list": + return {"ok": True, "max_running": 2, "sessions": []} + if args[0] == "repos": + return {"ok": True, "repos": ["a"], "add": {"base_url": "ssh://git@git.example:1/", "owners": ["team"]}} + if args[0] == "add-repo": + return {"ok": True, "repo": args[1], "repos": ["a", args[1]]} + if args[0] == "stop": + return {"ok": False, "error": "no session named 'x'"} + return {"ok": True} + + def setUp(self): + import http.client, threading + self.dev = self.FakeDev() + self.app = app.App({}, self.dev) + self.server = app.ThreadingHTTPServer(("127.0.0.1", 0), app.make_handler(self.app)) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self.addCleanup(self.server.server_close) + self.addCleanup(self.server.shutdown) + self.conn = lambda: http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=5) + + def request(self, method, path, body=None, **headers): + import urllib.parse + c = self.conn() + data = urllib.parse.urlencode(body).encode() if body is not None else None + hdrs = {"Remote-User": "reudy", "Sec-Fetch-Site": "same-origin", **headers} + if data is not None: + hdrs["Content-Type"] = "application/x-www-form-urlencoded" + c.request(method, path, data, hdrs) + r = c.getresponse() + return r, r.read() + + def test_page_and_assets(self): + r, body = self.request("GET", "/") + self.assertEqual(r.status, 200) + csp = r.getheader("Content-Security-Policy") + self.assertIn("script-src 'self'", csp) + self.assertNotIn("unsafe", csp) + for path in ("/app.js", "/app.css"): + r, body = self.request("GET", f"{path}?v={app.ASSET_VERSION}") + self.assertEqual(r.status, 200, path) + self.assertIn("immutable", r.getheader("Cache-Control")) + r, _ = self.request("GET", "/app.js", **{"Remote-User": ""}) + self.assertEqual(r.status, 403) + + def test_repos_are_cached_between_page_views(self): + self.request("GET", "/") + self.request("GET", "/") + self.assertEqual([c[0] for c in self.dev.calls].count("repos"), 1) + self.assertEqual([c[0] for c in self.dev.calls].count("list"), 2) + + def test_json_answers_instead_of_redirect(self): + import json + r, body = self.request("POST", "/start", {"name": "x"}, Accept="application/json") + self.assertEqual(r.status, 200) + self.assertEqual(json.loads(body), {"ok": True, "message": "Started x"}) + r, body = self.request("POST", "/stop", {"name": "x"}, Accept="application/json") + self.assertEqual(json.loads(body), {"ok": False, "error": "no session named 'x'"}) + r, _ = self.request("POST", "/start", {"name": "x"}) + self.assertEqual(r.status, 303) # without JS: post, redirect, get + + def test_cross_site_and_unauthenticated_posts_still_refused(self): + r, _ = self.request("POST", "/start", {"name": "x"}, Accept="application/json", **{"Sec-Fetch-Site": "cross-site"}) + self.assertEqual(r.status, 403) + r, _ = self.request("POST", "/start", {"name": "x"}, Accept="application/json", **{"Remote-User": ""}) + self.assertEqual(r.status, 403) + self.assertEqual(self.dev.calls, []) + + def test_add_repo_sends_only_owner_and_name(self): + import json + r, body = self.request("POST", "/add-repo", {"url": "ssh://git@git.example:1/team/My_App.git"}, + Accept="application/json") + out = json.loads(body) + self.assertTrue(out["ok"]) + self.assertEqual(out["repos"], ["a", "my-app"]) + self.assertIn(("add-repo", "my-app", "team/My_App"), self.dev.calls) + # the cache now has the new repo without another `repos` call + self.assertEqual(self.app.repos()["repos"], ["a", "my-app"]) + self.assertEqual([c[0] for c in self.dev.calls].count("repos"), 1) + + def test_add_repo_rejects_other_hosts_before_calling_the_dev_box(self): + import json + r, body = self.request("POST", "/add-repo", {"url": "https://github.com/team/x"}, Accept="application/json") + self.assertFalse(json.loads(body)["ok"]) + self.assertNotIn("add-repo", [c[0] for c in self.dev.calls]) + + if __name__ == "__main__": unittest.main()