Add sessions-ctl keygen to create prod's key on the dev box
keygen generates an ed25519 pair in RAM, writes the public half to config.toml and authorized_keys (replacing the previous sessions-manager line) and prints the web app's environment - dev host, port, user, pinned host key and the private key as one base64 line - then deletes the private key, so the pasted copy is the only one. Refuses to replace an existing key without --rotate. Local only, never reachable over SSH. Also make load_config() read CONFIG_PATH at call time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac
This commit is contained in:
parent
08636ddc25
commit
ca66db3aeb
4 changed files with 165 additions and 7 deletions
|
|
@ -18,13 +18,16 @@ Each session is:
|
|||
systemd is the source of truth for "should this run": a session that is
|
||||
enabled starts at boot (the user has linger on) and is restarted if it dies.
|
||||
|
||||
Output is always one JSON object on stdout. Exit codes: 0 ok, 1 error, 2 usage.
|
||||
Output is one JSON object on stdout (except `keygen`, which prints an env
|
||||
block to copy). Exit codes: 0 ok, 1 error, 2 usage.
|
||||
Standard library only, so it runs with the system python3.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime as dt
|
||||
import getpass
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
|
|
@ -47,6 +50,7 @@ CLAUDE_JSON = Path(os.environ.get("SESSIONS_CLAUDE_JSON", HOME / ".claude.json")
|
|||
CLAUDE_PROJECTS = HOME / ".claude/projects"
|
||||
AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys"))
|
||||
SELF_PATH = HOME / ".local/bin/sessions-ctl"
|
||||
HOST_KEY_PATH = os.environ.get("SESSIONS_HOST_KEY", "/etc/ssh/ssh_host_ed25519_key.pub")
|
||||
|
||||
UNIT = "claude-session@{}.service"
|
||||
KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys
|
||||
|
|
@ -74,7 +78,8 @@ class UserError(Exception):
|
|||
# ---------------------------------------------------------------- config/state
|
||||
|
||||
|
||||
def load_config(path: Path = CONFIG_PATH) -> dict:
|
||||
def load_config(path: Path | None = None) -> dict:
|
||||
path = path or CONFIG_PATH # looked up at call time, so tests can repoint it
|
||||
cfg = dict(DEFAULTS)
|
||||
if path.exists():
|
||||
with path.open("rb") as f:
|
||||
|
|
@ -399,6 +404,80 @@ def cmd_refresh_access(cfg: dict, args: list[str]) -> dict:
|
|||
return {"changed": changed, "from": ips}
|
||||
|
||||
|
||||
def cmd_keygen(cfg: dict, args: list[str]) -> dict:
|
||||
"""Local only. Make the key prod uses and print its env block once.
|
||||
|
||||
The pair is generated in RAM (XDG_RUNTIME_DIR). The public half goes into
|
||||
config.toml and authorized_keys; the private half is printed as one base64
|
||||
line for the container's environment and then deleted, so it exists only
|
||||
where you paste it.
|
||||
"""
|
||||
if [a for a in args if a != "--rotate"]:
|
||||
raise UserError("usage: sessions-ctl keygen [--rotate]")
|
||||
if cfg["ssh_access"].get("public_key", "").startswith("ssh-") and "--rotate" not in args:
|
||||
raise UserError("a key is already configured; `keygen --rotate` replaces it "
|
||||
"(prod stops working until its environment is updated)")
|
||||
if not cfg["ssh_access"].get("allow_from_host"):
|
||||
raise UserError("config: set ssh_access.allow_from_host first")
|
||||
|
||||
tmp = Path(tempfile.mkdtemp(dir=_user_env()["XDG_RUNTIME_DIR"], prefix="sessions-keygen-"))
|
||||
try:
|
||||
_run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "sessions-web", "-f", str(tmp / "id")])
|
||||
public = (tmp / "id.pub").read_text().strip()
|
||||
private_b64 = base64.b64encode((tmp / "id").read_bytes()).decode()
|
||||
finally:
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else ""
|
||||
atomic_write(CONFIG_PATH, set_toml_string(text, "ssh_access", "public_key", public), 0o600)
|
||||
access = cmd_refresh_access(load_config(), [])
|
||||
|
||||
host_key = " ".join(Path(HOST_KEY_PATH).read_text().split()[:2])
|
||||
env_block = "\n".join([
|
||||
f"SESSIONS_DEV_HOST={cfg['ssh_access'].get('advertise_host') or public_address()}",
|
||||
f"SESSIONS_DEV_PORT={cfg['ssh_access'].get('port', 14922)}",
|
||||
f"SESSIONS_DEV_USER={getpass.getuser()}",
|
||||
f"SESSIONS_DEV_HOST_KEY={host_key}",
|
||||
f"SESSIONS_SSH_KEY_B64={private_b64}",
|
||||
])
|
||||
note = ("Paste these lines into the sessions app's environment on prod (panel -> app -> Environment).\n"
|
||||
"The private key exists nowhere else now. Clear this screen afterwards (`clear`, and your\n"
|
||||
"terminal's scrollback). The key only works from: " + ", ".join(access["from"]))
|
||||
return {"text": env_block, "note": note, "from": access["from"]}
|
||||
|
||||
|
||||
def set_toml_string(text: str, section: str, key: str, value: str) -> str:
|
||||
"""Set `key = "value"` inside [section] of a simple TOML file, keeping the rest."""
|
||||
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:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("["):
|
||||
if in_section and not done:
|
||||
out.append(f'{key} = "{value}"')
|
||||
done = True
|
||||
in_section = stripped == f"[{section}]"
|
||||
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(line)
|
||||
if not done:
|
||||
if not in_section:
|
||||
out += ["", f"[{section}]"]
|
||||
out.append(f'{key} = "{value}"')
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def public_address() -> str:
|
||||
"""The source address this box uses to reach the internet (no packet is sent)."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("192.0.2.1", 9)) # TEST-NET-1; UDP connect only picks a route
|
||||
return s.getsockname()[0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- helpers
|
||||
|
||||
|
||||
|
|
@ -449,6 +528,7 @@ VERBS = {
|
|||
"health": cmd_health,
|
||||
"delete": cmd_delete,
|
||||
"refresh-access": cmd_refresh_access,
|
||||
"keygen": cmd_keygen,
|
||||
"_launch": cmd_launch,
|
||||
}
|
||||
|
||||
|
|
@ -484,7 +564,12 @@ def main(argv: list[str]) -> int:
|
|||
if not argv or argv[0] not in VERBS:
|
||||
raise UserError(f"usage: sessions-ctl {{{'|'.join(v for v in VERBS if not v.startswith('_'))}}} …")
|
||||
result = VERBS[argv[0]](load_config(), argv[1:])
|
||||
print(json.dumps({"ok": True, **result}))
|
||||
if "text" in result and not remote:
|
||||
print(result["text"]) # keygen: KEY=VALUE lines only, safe to paste as-is
|
||||
if result.get("note"):
|
||||
print(result["note"], file=sys.stderr)
|
||||
else:
|
||||
print(json.dumps({"ok": True, **result}))
|
||||
return 0
|
||||
except UserError as e:
|
||||
print(json.dumps({"ok": False, "error": str(e)}))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue