# ShellBook — Specification (draft v0.1) ShellBook is a self-hosted web app for **notebook-style runbooks for Linux servers**. A notebook is a Markdown file: prose plus shell blocks. The shell is the primary artifact — always shown literally, with parameter values filled in, copyable into any terminal. ShellBook adds buttons around it: run on a host over SSH, check a condition, download a produced file. Claude Code (the real CLI, subscription login) runs in a built-in terminal and edits the notebooks. ## 1. Goals | # | Requirement | Where | |---|---|---| | G1 | Notebooks with prose and code, written by hand or by AI | §3 format, §6 AI | | G2 | Run a code block on a chosen machine over SSH | §4 execution | | G3 | Check blocks that do real checks on the machine (dir/package/config present) and show ✅/❌ | §3.3 | | G4 | Parameters in the text: editable, optionally required, substituted into the scripts | §3.2 | | G5 | Dynamic flows: a step produces files → download buttons + follow-up notes appear | §3.4, §3.5 | | G6 | **Commands are readable and copyable** without running anything | §3.1, §5 | | G7 | Web UI, reachable over LAN/Tailscale behind Traefik; logins survive restarts | §7 | | G8 | Claude Code CLI with subscription login, as a chat-like panel next to the notebook | §6 | Non-goals (v1): multi-user roles, scheduling/cron, Windows targets, interactive TTY programs inside run blocks (use the terminal panel for those). ## 2. Concepts - **Workspace**: a git repo with the user's data, separate from the app code: `notebooks/*.md`, `hosts.yaml`, `CLAUDE.md` (format guide for Claude, shipped by ShellBook). - **Host**: an entry in `hosts.yaml` (`name`, `address`, `user`, `port`, optional `tags`). ShellBook connects with its own SSH key. - **Step**: a fenced block with a ShellBook attribute set. Kinds: `run`, `check`. - **Run record**: one execution of a step (host, rendered script, output, exit code, artifacts, timestamp). Appended to the audit log. ## 3. Notebook format Plain Markdown that renders sensibly in Gitea/GitHub too (blocks show as normal `sh` code with an info string). ### 3.1 Example ````markdown --- title: New server SSH key params: host: { type: host, required: true, label: Target server } user: { type: name, required: true, default: admin, label: Login user } keyname: { type: name, default: "id_ed25519_{{host}}" } --- # New server SSH key Creates a key pair for **{{user}}** on **{{host}}** and authorizes it. ```sh {check host="{{host}}" title="User exists"} id {{user}} ``` ```sh {check host="{{host}}" title="Password login disabled"} sshd -T | grep -qx 'passwordauthentication no' ``` ```sh {run on=local id=keygen title="Generate key pair" artifacts="{{keyname}},{{keyname}}.pub"} ssh-keygen -q -t ed25519 -N '' -C {{user}}@{{host}} -f {{keyname}} ``` ```sh {run host="{{host}}" id=authorize title="Authorize key" confirm upload="{{keyname}}.pub:/tmp/new_key.pub"} install -d -m 700 -o {{user}} -g {{user}} ~{{user}}/.ssh cat /tmp/new_key.pub >> ~{{user}}/.ssh/authorized_keys rm /tmp/new_key.pub ``` :::after{step=keygen} Download the private key above, then save it: - **Linux:** `~/.ssh/{{keyname}}`, then `chmod 600 ~/.ssh/{{keyname}}` - **Windows:** `C:\Users\\.ssh\{{keyname}}` ::: ```` ### 3.2 Parameters - Declared in frontmatter `params`. Fields: `type`, `required`, `default`, `label`, `options` (for `type: choice`). - Types and validation (validated before any run): - `host` — dropdown from `hosts.yaml`; substitutes the host **name** in attributes, the connection uses the inventory entry. - `name` — `[A-Za-z0-9._-]+` (users, files, packages, services). - `path` — absolute or relative path, no NUL/newline. - `string` — free text. - `choice` — one of `options`. - `secret` — never rendered, never logged; passed to the script as an environment variable only (`$NAME`), not via `{{ }}`. - `{{name}}` works in prose, in block attributes and in scripts. - **Substitution in scripts is shell-safe**: the value is inserted shell-quoted when it contains anything outside `[A-Za-z0-9._/@:=+-]`. The displayed script and the executed script are the same string. One function does this (`core/shellQuote`), nowhere else. - A step with a missing required param shows the script with `{{name}}` highlighted and a disabled Run button. ### 3.3 Step attributes Info string: `sh { key=value key="value with spaces" flag}`. Language `sh`/`bash` keeps syntax highlighting in other renderers. | Attribute | Kinds | Meaning | |---|---|---| | `run` / `check` | — | Step kind. `check` = read-only, ✅ if exit code 0, may run without confirmation ("Run all checks"). | | `host="…"` | both | Target host (usually `{{host}}`). | | `on=local` | both | Run on the ShellBook server instead (key generation, etc.). | | `id=…` | both | Stable id, referenced by `:::after` and `capture`. Default: slug of title. | | `title="…"` | both | Shown as step heading. | | `sudo` | both | Wrap in `sudo -n` (passwordless sudo required; fails clearly otherwise). | | `confirm` | run | Ask before running (default on for `run` against hosts tagged `prod`). | | `capture=var` | both | Store trimmed stdout as a runtime param `var` for later steps. | | `artifacts="a,b"` | run | Files (relative to the run's workdir) offered as downloads after success. Remote: fetched via SFTP. | | `upload="src:dst"` | run | Copy an artifact from a previous step to the host before the script runs. | | `timeout=60` | both | Seconds; default 300 for run, 30 for check. | ### 3.4 Conditional sections `:::after{step=}` … `:::` — rendered only after that step succeeded in the current session. `:::after{step= failed}` for the failure case. (remark-directive syntax.) ### 3.5 Artifacts Each `on=local` run gets a fresh workdir under `data/runs//`. Artifacts are kept for 24 h (configurable), then deleted. Private keys are flagged sensitive: one download only, then removed. ## 4. Execution - Scripts run as `bash -euo pipefail -s` with the script on stdin; no TTY. - SSH via `ssh2`, ShellBook's own key, **strict host key checking**. Unknown host key → UI shows the fingerprint and asks once (TOFU), then stored in the workspace's `known_hosts`. - Output is streamed to the browser over WebSocket (stdout/stderr interleaved, with exit code). - Every run is appended to `data/audit.jsonl`: time, notebook, step id, host, rendered script, exit code, duration. Secrets never appear. - One step per host at a time (queue); different hosts in parallel. ## 5. UI - **Notebook list** (left), **notebook view** (center), **AI/terminal panel** (right, collapsible). - Notebook view: params form at the top (sticky); prose rendered; each step is a card: title, target host, **the literal script with values filled in**, buttons `Copy` · `Copy as ssh one-liner` · `Run`/`Check`; output below. - "Run all checks" button per notebook → ✅/❌ summary. - Edit mode: raw Markdown in CodeMirror with live preview. Files changed on disk (by Claude or git pull) reload live. - Notebook management: searchable folder tree; create with name/folder/title and a valid starter, rename/move, duplicate, and explicitly confirmed delete. Paths are relative to `notebooks/`; folders are created as needed and pruned when empty. - Editor toolbar inserts checks, runs, artifact downloads, uploads, captures and after-step notes at the cursor. A parameter form edits YAML frontmatter through a YAML document parser; format help explains syntax. Targets are local or host parameters. Examples must be reviewed before execution. - Mutations use optimistic versions; occupied destinations or stale versions return 409. Atomic file publication and recursive watcher events refresh all tabs. An external rename/delete retains the old open draft with a notice and refreshes the tree; users can select the new path. Unsaved navigation requires confirmation. ## 6. AI: Claude Code - The right panel is a real terminal (xterm.js ↔ node-pty) running `claude` in the workspace, inside `tmux` so the session survives closed tabs and app restarts. This is the genuine CLI with the user's own subscription login — no API key, no SDK. - The workspace ships a `CLAUDE.md` describing this notebook format, so Claude writes shell-first notebooks (literal commands, no wrapper code). - Live reload (§5) makes Claude's edits appear immediately. - Later option: `ANTHROPIC_BASE_URL` / token for a custom endpoint, set in the panel's environment. ## 7. Security - The app can run commands on every host → treat access as root-equivalent. - Built-in login: one scrypt password hash in `auth.json`; session cookies are HMAC signed with a persisted mode-0600 secret and bound to the current password hash. Logins survive restarts; changing the password invalidates other cookies. - First run creates a random mode-0600 `setup-token` in the data directory. Only its path is logged. Public GET `/api/auth/setup` reports whether setup is needed; POST requires the token (constant-time comparison), matching passwords of at least 12 characters (maximum 4096 bytes), and consumes the token once. Configured instances reject setup with 409. Setup and login share a per-IP rate limit. - Settings changes require the current password, or atomically rotate the signing secret to sign out all sessions. Both issue a fresh cookie to the current browser and close existing WebSockets; future connections must authenticate again. Forward-auth identities remain governed by the upstream proxy. - Every API route is authenticated except exact health, login, and setup paths; the origin check also covers those exceptions and WebSocket upgrades. Optional forward-auth headers are accepted only from configured trusted peers. - Claude status executes only `claude --version` with argv, timeout, and output limit. Login status checks only the existence of `~/.claude/.credentials.json` under the service user home; credential contents are never read or returned. - Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only). - Terminal panel = shell as the service user: same trust level as the app itself. - No secrets in notebooks, audit log or artifacts metadata. ## 8. Architecture pnpm monorepo, TypeScript throughout, Node 22 LTS. ``` packages/core format parser (frontmatter, steps, directives), param validation, substitution + shellQuote. Pure, no I/O. Shared by server and web. apps/server Fastify + WebSocket. Workspace files, hosts.yaml, SSH (ssh2), run queue, artifacts, audit log, auth, terminal (node-pty + tmux), file watcher. apps/web Vite + React. Notebook view, params form, step cards, CodeMirror, xterm.js panel. deploy/ LXC/systemd install script, Traefik example. ``` Tests: Vitest. `core` is unit-tested exhaustively (parser, quoting, validation); server has integration tests against a throwaway SSH server container. ## 9. Milestones | M | Scope | Done when | |---|---|---| | M0 | Repo skeleton, `core`: parser, params, shellQuote + tests | Example §3.1 parses; quoting fuzz tests pass | | M1 | Read-only viewer: list, params form, rendered steps, copy buttons | Example notebook readable/copyable in browser | | M2 | Execution: hosts.yaml, SSH run/check, streaming, TOFU, audit log | Checks + run against a test VM | | M3 | Artifacts, uploads, `:::after`, `capture` | SSH-key example works end to end | | M4 | Terminal panel with Claude in tmux, live reload, shipped CLAUDE.md | Claude edits a notebook, view updates live | | M5 | Auth, deploy script for LXC 501, Traefik example; replaces marimo | Running in CT 501 behind Traefik |