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
This commit is contained in:
parent
39997de1e8
commit
1b3172bd50
10 changed files with 1084 additions and 92 deletions
|
|
@ -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
|
||||
|
|
|
|||
248
web/app.py
248
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"(?:(?P<scheme>ssh|https?)://(?:[A-Za-z0-9._-]+@)?(?P<host>[A-Za-z0-9.-]+)(?::\d+)?/"
|
||||
r"|git@(?P<scp_host>[A-Za-z0-9.-]+):)?"
|
||||
r"(?P<owner>[A-Za-z0-9][A-Za-z0-9._-]{0,39})/(?P<repo>[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 = ('<svg class="mark" viewBox="0 0 24 24" aria-hidden="true"><rect width="24" height="24" rx="6"/>'
|
||||
'<path d="M7 8l4 4-4 4M13 16h4" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>')
|
||||
|
||||
|
||||
def page(title: str, body: str) -> bytes:
|
||||
return f"""<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>{html.escape(title)}</title><link rel="stylesheet" href="/app.css"></head>
|
||||
<body><main>{body}</main></body></html>""".encode()
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>{html.escape(title)}</title><link rel="stylesheet" href="/app.css?v={ASSET_VERSION}">
|
||||
<script src="/app.js?v={ASSET_VERSION}" defer></script></head>
|
||||
<body>{body}</body></html>""".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'<form method="post" action="/{verb}" class="inline">'
|
||||
f'<input type="hidden" name="name" value="{e(name)}"><button>{verb.title()}</button></form>')
|
||||
f'<input type="hidden" name="name" value="{e(name)}">'
|
||||
f'<button class="btn {cls}">{verb.title()}</button></form>')
|
||||
|
||||
|
||||
def badge(state: str) -> str:
|
||||
return f'<span class="badge {e(state)}"><i></i>{e(STATE_LABEL.get(state, state.title()))}</span>'
|
||||
|
||||
|
||||
def session_card(s: dict, actions: str, cls: str = "") -> str:
|
||||
warn = f'<div class="warn">⚠ {e(s["needs_attention"])}</div>' if s.get("needs_attention") else ""
|
||||
warn = f'<div class="warn">{e(s["needs_attention"])}</div>' if s.get("needs_attention") else ""
|
||||
restarts = f' · restarted {e(s["restarts"])}×' if s.get("restarts") else ""
|
||||
return f"""<div class="card {cls}"><div class="row"><span class="name">{e(s.get("title") or s["name"])}</span>
|
||||
<span class="pill {e(s["state"])}">{e(s["state"])}</span></div>
|
||||
<div class="meta">{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}</div>{warn}
|
||||
<div class="actions">{actions}</div></div>"""
|
||||
linked = " data-linked" if s.get("remote_control_url") else ""
|
||||
created = e(s["created_at"])
|
||||
return f"""<article class="card {cls}" data-name="{e(s["name"])}" data-state="{e(s["state"])}"{linked}>
|
||||
<div class="card-top"><h3 class="title">{e(s.get("title") or s["name"])}</h3>{badge(s["state"])}</div>
|
||||
<div class="meta"><span class="mono">{e(s["repo"])}</span><span class="dim">/</span><span class="mono">{e(s["branch"])}</span></div>
|
||||
<div class="meta dim">Created <time datetime="{created}">{e(s["created_at"][:16].replace("T", " "))}</time>{restarts}</div>{warn}
|
||||
<div class="actions">{actions}</div></article>"""
|
||||
|
||||
|
||||
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
|
||||
parts = [f'<header><h1>Sessions</h1><span class="meta">{e(user)}</span></header>']
|
||||
if flash:
|
||||
parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>')
|
||||
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'<div class="flash err">{e(listing.get("error", "dev box error"))}</div>')
|
||||
parts.append(f'<div class="callout err">{e(listing.get("error", "dev box error"))}</div>')
|
||||
sessions = [s for s in listing.get("sessions", []) if not s.get("archived")]
|
||||
archived = [s for s in listing.get("sessions", []) if s.get("archived")]
|
||||
running = sum(1 for s in sessions if s["state"] == "active")
|
||||
parts.append(f'<h2>Running {running} of {e(listing.get("max_running", "?"))}</h2>')
|
||||
if not sessions and listing.get("ok"):
|
||||
parts.append('<p class="meta">No sessions yet.</p>')
|
||||
parts.append(f'<div class="section-head"><h2>Active</h2>'
|
||||
f'<span class="counter">{running} of {e(listing.get("max_running", "?"))} running</span></div>')
|
||||
cards = []
|
||||
for s in sessions:
|
||||
link = (f'<a class="btn primary" href="{e(s["remote_control_url"])}" rel="noopener">Open in Claude</a>'
|
||||
if s.get("remote_control_url") and s["state"] == "active" else "")
|
||||
verb = "stop" if s["enabled"] else "start"
|
||||
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('<div class="empty"><strong>No sessions yet</strong>'
|
||||
'<span>Create one and it shows up here and in the Claude app.</span></div>')
|
||||
parts.append(f'<div class="list">{"".join(cards)}</div>')
|
||||
if archived:
|
||||
cards = "".join(session_card(s, action("unarchive", s["name"]), "archived") for s in archived)
|
||||
parts.append(f'<details><summary><h2>Archived ({len(archived)})</h2></summary>{cards}</details>')
|
||||
old = "".join(session_card(s, action("unarchive", s["name"], "secondary"), "archived") for s in archived)
|
||||
parts.append(f'<details class="archive"><summary>Archived <span class="count">{len(archived)}</span></summary>'
|
||||
f'<div class="list">{old}</div></details>')
|
||||
return f'<div id="live">{"".join(parts)}</div>'
|
||||
|
||||
|
||||
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
|
||||
toast = f'<div class="toast {e(flash[0])}" role="status">{e(flash[1])}</div>' if flash else ""
|
||||
options = "".join(f'<option value="{e(r)}">{e(r)}</option>' for r in repos.get("repos", []))
|
||||
parts.append(f"""<h2>New session</h2><form method="post" action="/create" class="card">
|
||||
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"""<details class="panel" id="add-panel"><summary><h2>Add repository</h2></summary>
|
||||
<form method="post" action="/add-repo" id="add-repo">
|
||||
<label for="repo-url">Clone URL or owner/name</label>
|
||||
<input id="repo-url" name="url" required maxlength="200" placeholder="{e(add["owners"][0])}/my-app" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<label for="repo-key">Short name <span class="opt">optional</span></label>
|
||||
<input id="repo-key" name="key" maxlength="32" pattern="[a-z0-9][a-z0-9\\-]{{0,31}}" placeholder="from the repo name" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<p class="hint">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.</p>
|
||||
<div class="actions"><button class="btn secondary">Add repository</button></div></form></details>"""
|
||||
|
||||
body = f"""<header class="top"><div class="wrap top-inner">
|
||||
<a class="brand" href="/">{MARK}<span>Sessions</span></a><span class="user">{e(user)}</span></div></header>
|
||||
<div id="toasts" aria-live="polite">{toast}</div>
|
||||
<main class="wrap grid">
|
||||
<section class="col-main">
|
||||
<div class="intro"><h1>Sessions</h1><p>Claude Code on the dev box, with Remote Control.</p></div>
|
||||
{live_section(listing)}
|
||||
</section>
|
||||
<aside class="col-side">
|
||||
<form method="post" action="/create" class="panel" id="create">
|
||||
<h2>New session</h2>
|
||||
<label for="name">Name</label><input id="name" name="name" required maxlength="48" pattern="[A-Za-z0-9][A-Za-z0-9 \\-]{{0,47}}" placeholder="Fix login bug" autocomplete="off">
|
||||
<label for="repo">Repository</label><select id="repo" name="repo" required>{options}</select>
|
||||
<label for="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off">
|
||||
<div class="actions"><button class="primary">Create</button><a class="btn" href="/">Refresh</a></div></form>
|
||||
<p class="meta">A session runs Claude Code on the dev box with Remote Control on. Give it instructions from the Claude app or the “Open in Claude” link — never from this page.</p>""")
|
||||
return page("Sessions", "".join(parts))
|
||||
<label for="base">Start from branch <span class="opt">optional</span></label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off" spellcheck="false">
|
||||
<div class="actions"><button class="btn primary wide">Create session</button><a class="btn ghost" href="/" data-refresh>Refresh</a></div>
|
||||
</form>
|
||||
{add_form}
|
||||
<p class="note">Give a session instructions from the Claude app or the “Open in Claude” link — never from this page.</p>
|
||||
</aside>
|
||||
</main>"""
|
||||
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})})
|
||||
|
||||
|
|
|
|||
254
web/static/app.css
Normal file
254
web/static/app.css
Normal file
|
|
@ -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; }
|
||||
}
|
||||
224
web/static/app.js
Normal file
224
web/static/app.js
Normal file
|
|
@ -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 = '<div class="card-top"><h3 class="title"></h3>' +
|
||||
'<span class="badge activating"><i></i>Cloning</span></div><div class="meta"><span class="mono"></span></div>';
|
||||
$(".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();
|
||||
})();
|
||||
|
|
@ -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("<details>")
|
||||
live, archived = out.split('<details class="archive">')
|
||||
self.assertIn("LIVE", live)
|
||||
self.assertIn('action="/archive"', live)
|
||||
self.assertNotIn("OLD", live)
|
||||
self.assertIn("Archived (1)", archived)
|
||||
self.assertIn('Archived <span class="count">1</span>', archived)
|
||||
self.assertIn('action="/unarchive"', archived)
|
||||
self.assertNotIn('action="/start"', archived)
|
||||
no_archive = app.dashboard({"ok": True, "max_running": 2, "sessions": [s("live", False)]}, {}, "u", None)
|
||||
self.assertNotIn(b"<details>", no_archive)
|
||||
self.assertNotIn(b'<details class="archive">', 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"<script(?![^>]*\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()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue