# Conflicts: # .agents/mind/architecture.md # apps/server/src/app.ts # apps/web/src/App.tsx # packages/core/src/protocol.ts
270 lines
15 KiB
Markdown
270 lines
15 KiB
Markdown
# 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`).
|
|
Authentication is chosen per host in the Servers & SSH page (see ?4.1).
|
|
- **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\<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`, per-host authentication, **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.
|
|
|
|
### 4.1 Hosts and SSH credentials
|
|
|
|
The Servers & SSH page manages host name, address, user, port and tags without YAML
|
|
editing. Changes preserve YAML comments/order where practical and use an opaque
|
|
inventory version; stale writes return 409. Host renames migrate stored credentials;
|
|
notebook host references remain literal and must be updated by the user. The file
|
|
watcher publishes `file.changed` / `file.deleted` with path `hosts.yaml`.
|
|
|
|
Per-host authentication is ShellBook key (default), password (including non-echoed
|
|
keyboard-interactive password prompts), or private key with optional passphrase.
|
|
Paste or upload the key from the browser. ssh2 1.17.0 does not expose client user
|
|
certificate pairing; the UI explicitly disables OpenSSH certificates. All remote
|
|
execution, checks, uploads and artifact downloads use the same authenticated client.
|
|
Strict host key checks and explicit TOFU acceptance remain mandatory.
|
|
|
|
Passwords, private keys and passphrases are stored only in the data directory,
|
|
AES-256-GCM encrypted with random 96-bit nonces and host-name AAD. A random 256-bit
|
|
key file and credential files have POSIX mode 0600; ciphertext updates use atomic
|
|
rename. Keep dataDir outside the workspace repository. APIs never return stored
|
|
secrets: only type, key fingerprint (when applicable), and set-at time. Selecting
|
|
the default or deleting a host deletes its credential. Credential values join the
|
|
existing streaming/audit redaction list; host actions discard remote output and
|
|
return only an exit status or a TOFU fingerprint challenge.
|
|
|
|
The page shows the ShellBook public key with Copy, Test connection (`true`),
|
|
Install ShellBook key, and Forget host key. Installation requires the stored
|
|
password and previews the literal script; the server rejects a mismatched preview
|
|
before connecting. It appends the public key idempotently to the remote user's
|
|
`~/.ssh/authorized_keys`, with all quoting through core `shellQuote`. The password
|
|
remains selected until the user chooses ShellBook key after successful installation.
|
|
Forgetting a host key requires UI confirmation and removes only that endpoint,
|
|
preserving other aliases. All management routes use the existing session and origin
|
|
checks and responses disable caching.
|
|
|
|
## 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 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 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 |
|