Files
ShellBook/docs/spec.md
T

11 KiB

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 behind chat or 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

---
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\<you>\.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 {<kind> 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=<id>} … ::: — rendered only after that step succeeded in the current session. :::after{step=<id> failed} for the failure case. (remark-directive syntax.)

3.5 Artifacts

Each on=local run gets a fresh workdir under data/runs/<run-id>/. 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.

6. AI: Claude Code

  • The right panel offers chat and a real terminal. Both use the real claude CLI with the user's own subscription login; no API key or embedded SDK.
  • Chat runs one headless CLI process per turn (-p, stream-json stdin/stdout), in the workspace, with explicit --resume of the CLI session ID. A dedicated, authenticated same-origin /api/chat WebSocket streams text deltas, compact tool summaries, completion metadata and safe errors. Disconnect/Stop/timeout terminate the process; only one active turn per conversation is allowed.
  • File tools are restricted to workspace working directories using CLI restricted mode (Claude Code 2.1.248+). Available tools are Read, Glob, Grep, Edit, Write, MultiEdit; Bash is added only by the off-by-default shell-command toggle. Web and MCP tools are unavailable. Never use bypassPermissions.
  • The data directory persists conversation titles (first message), session IDs and timestamps, not messages or tool contents. The CLI keeps its own session transcripts. Never send secrets in chat. History resumes CLI context; the web view retains messages only for the lifetime of the mounted panel.
  • The terminal (xterm.js and node-pty) uses tmux, so interactive sessions survive closed tabs and app restarts. Missing CLI/login errors offer this panel with instructions to run claude, then /login.
  • The workspace ships a CLAUDE.md describing the notebook format. The chat appends ShellBook context and the open notebook path to the system prompt. Live reload (section 5) makes actual notebook edits appear immediately.
  • Details, resource limits and verified CLI flags: apps/server/src/chat/README.md.

7. Security

  • The app can run commands on every host → treat access as root-equivalent.
  • Built-in login: one password (scrypt hash in config), session cookie signed with a secret persisted on disk → logins survive restarts. Optional: trust a forward-auth header from Traefik instead.
  • 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